[Terraform] OpenStack Provider

gununoo·2022년 10월 25일
1

Terraform

목록 보기
2/3
post-thumbnail

Workspace

  • 개발자가 tf 파일에 접근하여 구성하고 있다면 다른 사용자의 접근은 차단된다. 동시 작업 불가.
  • 최종 상태 구성 파일 tfstate도 하나가 생긴다. 만약 손실이 발생한다면 전체 인프라에 영향을 미친다.
  • 이를 막기 위해 각각의 리소스 별로 디렉토리를 구분하여 작업한다. Ansible에서 role처럼 구분하여 작업하자.
  • tfstate가 손실될 위험에 대비하여 로컬 환경에 저장하지 말고 원격 공유 저장소에 저장하자.
  • k8s의 namespace처럼 작업 공간을 분류하자.

  • 작업공간 보기

    terraform workspace list

[root@terraform lab1]# terraform workspace list 
* default
  • 작업공간 생성하기
    terraform workspace new [workspace 이름]
[root@terraform lab1]# terraform workspace new blockstore 
Created and switched to workspace "blockstore"!

You're now on a new, empty workspace. Workspaces isolate their state,
so if you run "terraform plan" Terraform will not see any existing state
for this configuration.
  • 작업공간 확인
[root@terraform lab1]# terraform workspace list 
  default
* blockstore

blockstore에서 작업 중임

[root@terraform lab1]# tree 
.
├── instance.tf
├── main.tf
├── terraform.tfstate
├── terraform.tfstate.backup
└── terraform.tfstate.d
    └── blockstore

2 directories, 4 files

blockstore라는 작업 공간이 생성되었음

  • 작업공간 변경
[root@terraform lab1]# terraform workspace select default 
Switched to workspace "default".
[root@terraform lab1]# terraform workspace list 
* default
  blockstore
  • 작업공간 삭제
[root@terraform lab1]# terraform workspace delete blockstore 
Deleted workspace "blockstore"!
  • 삭제 확인
[root@terraform lab1]# tree 
.
├── instance.tf
├── main.tf
├── terraform.tfstate
├── terraform.tfstate.backup
└── terraform.tfstate.d

1 directory, 4 files

blockstore 작업 공간이 삭제되었음

실습

  • admin 접속
[root@localhost ~]# source keystonerc_admin 
  • 이미지 확인
[root@localhost ~(admin)]# openstack image list 
+--------------------------------------+---------+--------+
| ID                                   | Name    | Status |
+--------------------------------------+---------+--------+
| 5112e14c-3355-459f-8bad-e2881dc838f5 | CentOS7 | active |
| 519f20f8-3da6-4fd6-bf3c-da1ceb452a26 | cirros  | active |
+--------------------------------------+---------+--------+
  • 네트워크 확인
+--------------------------------------+----------+--------------------------------------+
| ID                                   | Name     | Subnets                              |
+--------------------------------------+----------+--------------------------------------+
| 98facebd-53fc-4a1c-80be-013026471da4 | extnet   | d87ef435-045a-4bbe-9526-31d09f1340d5 |
| ab0bc22b-f90b-49a2-8182-9a458101620f | private1 | 24301178-33c1-4c7b-922e-9fd13ea4ec12 |
+--------------------------------------+----------+--------------------------------------+

키페어

  • 키페어 생성
  • 키페어 생성 확인
[root@localhost ~(admin)]# openstack keypair list 
+--------------+-------------------------------------------------+------+
| Name         | Fingerprint                                     | Type |
+--------------+-------------------------------------------------+------+
| terraformkey | 29:04:26:f2:87:ef:49:2c:f4:1b:2a:43:1b:71:a6:84 | ssh  |
+--------------+-------------------------------------------------+------+

보안그룹

  • 보안그룹 생성
  • webssh 보안그룹
    • http, https, ssh 추가
  • icmp 보안그룹
    • icmp 추가

provider.tf

[root@terraform lab2]# touch provider.tf instance.tf 
[root@terraform lab2]# terraform init 

Initializing the backend...

Initializing provider plugins...

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
[root@terraform lab2]# vi provider.tf 
terraform {
required_version = ">= 1.0.0"
	required_providers {
		openstack = {
			source = "terraform-provider-openstack/openstack"
			version = "~> 1.42.0"
		}
	}
}

# api login 
provider "openstack" {
	user_name = "admin"
	password = "test123"
	tenant_name = "admin"
	auth_url = "http://211.183.3.160:5000"
	region = "RegionOne"
}

instance.tf

[root@terraform lab2]# vi instance.tf 
resource "openstack_compute_instance_v2" "instance01" {
	name = "instance01"
	image_name = "CentOS7"
	flavor_name = "m1.medium"
	key_pair = "terraformkey"
	security_groups = ["webssh", "icmp"]
	metadata = { key1 = "value" }
	network {
		name = "private1"
	}
}
[root@terraform lab2]# terraform apply -auto-approve

Terraform used the selected providers to generate the following execution plan. Resource actions are
indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # openstack_compute_instance_v2.instance01 will be created
  + resource "openstack_compute_instance_v2" "instance01" {
      + access_ip_v4        = (known after apply)
      + access_ip_v6        = (known after apply)
      + all_metadata        = (known after apply)
      + all_tags            = (known after apply)
      + availability_zone   = (known after apply)
      + flavor_id           = (known after apply)
      + flavor_name         = "m1.medium"
      + force_delete        = false
      + id                  = (known after apply)
      + image_id            = (known after apply)
      + image_name          = "CentOS7"
      + key_pair            = "terraformkey"
      + metadata            = {
          + "key1" = "value"
        }
      + name                = "instance01"
      + power_state         = "active"
      + region              = (known after apply)
      + security_groups     = [
          + "icmp",
          + "webssh",
        ]
      + stop_before_destroy = false

      + network {
          + access_network = false
          + fixed_ip_v4    = (known after apply)
          + fixed_ip_v6    = (known after apply)
          + floating_ip    = (known after apply)
          + mac            = (known after apply)
          + name           = "private1"
          + port           = (known after apply)
          + uuid           = (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.
openstack_compute_instance_v2.instance01: Creating...
openstack_compute_instance_v2.instance01: Still creating... [10s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [20s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [30s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [40s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [50s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [1m0s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [1m10s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [1m20s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [1m30s elapsed]
openstack_compute_instance_v2.instance01: Creation complete after 1m31s [id=0cb8e643-8906-4a1a-9560-068af3ae666e]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
  • 인스턴스 생성 확인
  • 인스턴스 콘솔 접속
  • 인스턴스 제거
[root@terraform lab2]# terraform destroy 

openstack_compute_instance_v2.instance01: Destroying... [id=0cb8e643-8906-4a1a-9560-068af3ae666e]
openstack_compute_instance_v2.instance01: Still destroying... [id=0cb8e643-8906-4a1a-9560-068af3ae666e, 10s elapsed]
openstack_compute_instance_v2.instance01: Destruction complete after 12s

Destroy complete! Resources: 1 destroyed.

  • 사설 ip 출력하도록 instance.tf 수정
[root@terraform lab2]# vi instance.tf 
resource "openstack_compute_instance_v2" "instance01" {
	name = "instance01" 
	image_name = "CentOS7"
	flavor_name = "m1.small"
	key_pair = "terraformkey"
	security_groups = ["webssh", "icmp"]
	
	metadata = {
		server = "web",
		color = "blue" 
	}
	
	network {
		name = "private1"
	}
}

output "private_address" {
	value = "${openstack_compute_instance_v2.instance01.network.0.fixed_ip_v4}"
}
[root@terraform lab2]# terraform apply -auto-approve

Terraform used the selected providers to generate the following execution plan. Resource actions are
indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # openstack_compute_instance_v2.instance01 will be created
  + resource "openstack_compute_instance_v2" "instance01" {
      + access_ip_v4        = (known after apply)
      + access_ip_v6        = (known after apply)
      + all_metadata        = (known after apply)
      + all_tags            = (known after apply)
      + availability_zone   = (known after apply)
      + flavor_id           = (known after apply)
      + flavor_name         = "m1.small"
      + force_delete        = false
      + id                  = (known after apply)
      + image_id            = (known after apply)
      + image_name          = "CentOS7"
      + key_pair            = "terraformkey"
      + metadata            = {
          + "color"  = "blue"
          + "server" = "web"
        }
      + name                = "instance01"
      + power_state         = "active"
      + region              = (known after apply)
      + security_groups     = [
          + "icmp",
          + "webssh",
        ]
      + stop_before_destroy = false

      + network {
          + access_network = false
          + fixed_ip_v4    = (known after apply)
          + fixed_ip_v6    = (known after apply)
          + floating_ip    = (known after apply)
          + mac            = (known after apply)
          + name           = "private1"
          + port           = (known after apply)
          + uuid           = (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + private_address = (known after apply)
openstack_compute_instance_v2.instance01: Creating...
openstack_compute_instance_v2.instance01: Still creating... [10s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [20s elapsed]
openstack_compute_instance_v2.instance01: Still creating... [30s elapsed]
openstack_compute_instance_v2.instance01: Creation complete after 32s [id=5d822e36-1146-47ec-a7e3-41a35980fb5e]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

private_address = "192.168.101.222"

192.168.101.222


openstack_compute_secgroup_v2

  • terraform을 통해 보안그룹 생성
[root@terraform lab2]# vi instance.tf 
# create openstack security_groups 
resource "openstack_compute_secgroup_v2" "tf_httpssh" {
	name = "op_httpssh"
	description = "permit http, ssh traffic from anywhere"
	
	rule {
		from_port = 80 // security_group's port 
		to_port = 80 // instance's port
		ip_protocol = "tcp" 
		cidr = "0.0.0.0/0" // permit from anywhere
	}

	rule {
		from_port = 22 // security_group's port
		to_port = 22 // instance's port
		ip_protocol = "tcp" 
		cidr = "0.0.0.0/0" // permit from anywhere
	}
}


resource "openstack_compute_instance_v2" "instance01" {
	name = "instance01" 
	image_name = "CentOS7"
	flavor_name = "m1.small"
	key_pair = "terraformkey"
	security_groups = ["op_httpssh", "icmp"]
	
	metadata = {
		server = "web",
		color = "blue" 
	}
	
	network {
		name = "private1"
	}
}

output "private_address" {
	value = "${openstack_compute_instance_v2.instance01.network.0.fixed_ip_v4}"
}

[root@terraform lab2]# terraform apply -auto-approve 

Terraform used the selected providers to generate the following execution plan. Resource actions are
indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # openstack_compute_instance_v2.instance01 will be created
  + resource "openstack_compute_instance_v2" "instance01" {
      + access_ip_v4        = (known after apply)
      + access_ip_v6        = (known after apply)
      + all_metadata        = (known after apply)
      + all_tags            = (known after apply)
      + availability_zone   = (known after apply)
      + flavor_id           = (known after apply)
      + flavor_name         = "m1.small"
      + force_delete        = false
      + id                  = (known after apply)
      + image_id            = (known after apply)
      + image_name          = "CentOS7"
      + key_pair            = "terraformkey"
      + metadata            = {
          + "color"  = "blue"
          + "server" = "web"
        }
      + name                = "instance01"
      + power_state         = "active"
      + region              = (known after apply)
      + security_groups     = [
          + "icmp",
          + "op_httpssh",
        ]
      + stop_before_destroy = false

      + network {
          + access_network = false
          + fixed_ip_v4    = (known after apply)
          + fixed_ip_v6    = (known after apply)
          + floating_ip    = (known after apply)
          + mac            = (known after apply)
          + name           = "private1"
          + port           = (known after apply)
          + uuid           = (known after apply)
        }
    }

  # openstack_compute_secgroup_v2.tf_httpssh will be created
  + resource "openstack_compute_secgroup_v2" "tf_httpssh" {
      + description = "permit http, ssh traffic from anywhere"
      + id          = (known after apply)
      + name        = "op_httpssh"
      + region      = (known after apply)

      + rule {
          + cidr        = "0.0.0.0/0"
          + from_port   = 22
          + id          = (known after apply)
          + ip_protocol = "tcp"
          + self        = false
          + to_port     = 22
        }
      + rule {
          + cidr        = "0.0.0.0/0"
          + from_port   = 80
          + id          = (known after apply)
          + ip_protocol = "tcp"
          + self        = false
          + to_port     = 80
        }
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + private_address = (known after apply)
openstack_compute_secgroup_v2.tf_httpssh: Creating...
openstack_compute_instance_v2.instance01: Creating...
openstack_compute_secgroup_v2.tf_httpssh: Creation complete after 6s [id=36676d0f-1c71-46b9-8816-4141dbe31bb4]
openstack_compute_instance_v2.instance01: Still creating... [10s elapsed]
openstack_compute_instance_v2.instance01: Creation complete after 20s [id=3882ad89-f57f-4835-be51-75f61280aa50]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:

private_address = "192.168.101.233"

새로 생성한 보안그룹에 192.168.101.223 인스턴스 생성되었음

Floating IP

[root@terraform lab2]# vi instance.tf 
  • 아래 코드를 추가
#################### floating ip ####################
resource "openstack_networking_floatingip_v2" "fip1" {
	pool = "extnet"
}

resource "openstack_compute_floatingip_associate_v2" "fip1" {
	floating_ip = "${openstack_networking_floatingip_v2.fip1.address}"
	instance_id = "${openstack_compute_instance_v2.instance01.id}"
	fixed_ip = "${openstack_compute_instance_v2.instance01.network.0.fixed_ip_v4}"
}
  • 전체 코드
# create openstack security_groups 
resource "openstack_compute_secgroup_v2" "tf_httpssh" {
	name = "op_httpssh"
	description = "permit http, ssh traffic from anywhere"
	
	rule {
		from_port = 80 // security_group's port 
		to_port = 80 // instance's port
		ip_protocol = "tcp" 
		cidr = "0.0.0.0/0" // permit from anywhere
	}

	rule {
		from_port = 22 // security_group's port
		to_port = 22 // instance's port
		ip_protocol = "tcp" 
		cidr = "0.0.0.0/0" // permit from anywhere
	}
}


resource "openstack_compute_instance_v2" "instance01" {
	name = "instance01" 
	image_name = "CentOS7"
	flavor_name = "m1.small"
	key_pair = "terraformkey"
	security_groups = ["op_httpssh", "icmp"]
	
	metadata = {
		server = "web",
		color = "blue" 
	}
	
	network {
		name = "private1"
	}
}

#################### floating ip ####################
resource "openstack_networking_floatingip_v2" "fip1" {
	pool = "extnet"
}

resource "openstack_compute_floatingip_associate_v2" "fip1" {
	floating_ip = "${openstack_networking_floatingip_v2.fip1.address}"
	instance_id = "${openstack_compute_instance_v2.instance01.id}"
	fixed_ip = "${openstack_compute_instance_v2.instance01.network.0.fixed_ip_v4}"
}


output "private_address" {
	value = "${openstack_compute_instance_v2.instance01.network.0.fixed_ip_v4}"
}
  • terraform apply
[root@terraform lab2]# terraform apply -auto-approve 
openstack_networking_floatingip_v2.fip1: Refreshing state... [id=10ef5570-e98f-4a2d-8dca-756629b28fb8]
openstack_compute_instance_v2.instance01: Refreshing state... [id=3882ad89-f57f-4835-be51-75f61280aa50]openstack_compute_secgroup_v2.tf_httpssh: Refreshing state... [id=36676d0f-1c71-46b9-8816-4141dbe31bb4]
Terraform used the selected providers to generate the following execution plan. Resource actions are
indicated with the following symbols:
  + create
  ~ update in-place

Terraform will perform the following actions:

  # openstack_compute_floatingip_associate_v2.fip1 will be created
  + resource "openstack_compute_floatingip_associate_v2" "fip1" {
      + fixed_ip    = "192.168.101.233"
      + floating_ip = "211.183.3.212"
      + id          = (known after apply)
      + instance_id = "3882ad89-f57f-4835-be51-75f61280aa50"
      + region      = (known after apply)
    }

  # openstack_compute_instance_v2.instance01 will be updated in-place
  ~ resource "openstack_compute_instance_v2" "instance01" {
        id                  = "3882ad89-f57f-4835-be51-75f61280aa50"
        name                = "instance01"
      ~ security_groups     = [
          + "op_httpssh",
            # (1 unchanged element hidden)
        ]
        tags                = []
        # (14 unchanged attributes hidden)

        # (1 unchanged block hidden)
    }

Plan: 1 to add, 1 to change, 0 to destroy.
openstack_compute_instance_v2.instance01: Modifying... [id=3882ad89-f57f-4835-be51-75f61280aa50]
openstack_compute_instance_v2.instance01: Modifications complete after 9s [id=3882ad89-f57f-4835-be51-75f61280aa50]
openstack_compute_floatingip_associate_v2.fip1: Creating...
openstack_compute_floatingip_associate_v2.fip1: Creation complete after 5s [id=211.183.3.212/3882ad89-f57f-4835-be51-75f61280aa50/192.168.101.233]

Apply complete! Resources: 1 added, 1 changed, 0 destroyed.

Outputs:

private_address = "192.168.101.233"

192.168.101.233

인스턴스 여러 개 만들기

[root@terraform lab2]# vi instance.tf 
# create openstack security_groups 
resource "openstack_compute_secgroup_v2" "tf_httpssh" {
	name = "op_httpssh"
	description = "permit http, ssh traffic from anywhere"
	
	rule {
		from_port = 80 // security_group's port 
		to_port = 80 // instance's port
		ip_protocol = "tcp" 
		cidr = "0.0.0.0/0" // permit from anywhere
	}

	rule {
		from_port = 22 // security_group's port
		to_port = 22 // instance's port
		ip_protocol = "tcp" 
		cidr = "0.0.0.0/0" // permit from anywhere
	}
}


resource "openstack_compute_instance_v2" "instance" {
	name = "instance-${count.index + 1}" 
	image_name = "CentOS7"
	flavor_name = "m1.small"
	key_pair = "terraformkey"
	security_groups = ["op_httpssh", "icmp"]
	count = 2 
	
	network {
		name = "private1"
	}
}
	name = "instance-${count.index + 1}" 
	count = 2 
  • terraform apply

[root@terraform lab2]# terraform apply -auto-approve 

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # openstack_compute_instance_v2.instance[0] will be created
  + resource "openstack_compute_instance_v2" "instance" {
      + access_ip_v4        = (known after apply)
      + access_ip_v6        = (known after apply)
      + all_metadata        = (known after apply)
      + all_tags            = (known after apply)
      + availability_zone   = (known after apply)
      + flavor_id           = (known after apply)
      + flavor_name         = "m1.small"
      + force_delete        = false
      + id                  = (known after apply)
      + image_id            = (known after apply)
      + image_name          = "CentOS7"
      + key_pair            = "terraformkey"
      + name                = "instance-1"
      + power_state         = "active"
      + region              = (known after apply)
      + security_groups     = [
          + "icmp",
          + "op_httpssh",
        ]
      + stop_before_destroy = false

      + network {
          + access_network = false
          + fixed_ip_v4    = (known after apply)
          + fixed_ip_v6    = (known after apply)
          + floating_ip    = (known after apply)
          + mac            = (known after apply)
          + name           = "private1"
          + port           = (known after apply)
          + uuid           = (known after apply)
        }
    }

  # openstack_compute_instance_v2.instance[1] will be created
  + resource "openstack_compute_instance_v2" "instance" {
      + access_ip_v4        = (known after apply)
      + access_ip_v6        = (known after apply)
      + all_metadata        = (known after apply)
      + all_tags            = (known after apply)
      + availability_zone   = (known after apply)
      + flavor_id           = (known after apply)
      + flavor_name         = "m1.small"
      + force_delete        = false
      + id                  = (known after apply)
      + image_id            = (known after apply)
      + image_name          = "CentOS7"
      + key_pair            = "terraformkey"
      + name                = "instance-2"
      + power_state         = "active"
      + region              = (known after apply)
      + security_groups     = [
          + "icmp",
          + "op_httpssh",
        ]
      + stop_before_destroy = false

      + network {
          + access_network = false
          + fixed_ip_v4    = (known after apply)
          + fixed_ip_v6    = (known after apply)
          + floating_ip    = (known after apply)
          + mac            = (known after apply)
          + name           = "private1"
          + port           = (known after apply)
          + uuid           = (known after apply)
        }
    }

  # openstack_compute_secgroup_v2.tf_httpssh will be created
  + resource "openstack_compute_secgroup_v2" "tf_httpssh" {
      + description = "permit http, ssh traffic from anywhere"
      + id          = (known after apply)
      + name        = "op_httpssh"
      + region      = (known after apply)

      + rule {
          + cidr        = "0.0.0.0/0"
          + from_port   = 22
          + id          = (known after apply)
          + ip_protocol = "tcp"
          + self        = false
          + to_port     = 22
        }
      + rule {
          + cidr        = "0.0.0.0/0"
          + from_port   = 80
          + id          = (known after apply)
          + ip_protocol = "tcp"
          + self        = false
          + to_port     = 80
        }
    }

Plan: 3 to add, 0 to change, 0 to destroy.
openstack_compute_instance_v2.instance[0]: Creating...
openstack_compute_instance_v2.instance[1]: Creating...
openstack_compute_secgroup_v2.tf_httpssh: Creating...
openstack_compute_secgroup_v2.tf_httpssh: Creation complete after 4s [id=6d498433-0e25-431c-9ff5-a69c0102c296]
openstack_compute_instance_v2.instance[0]: Still creating... [10s elapsed]
openstack_compute_instance_v2.instance[1]: Still creating... [10s elapsed]
openstack_compute_instance_v2.instance[0]: Creation complete after 17s [id=626207ac-5a95-4386-82db-05de098af83f]
openstack_compute_instance_v2.instance[1]: Creation complete after 18s [id=36557c92-ecf0-44c2-881c-40d23a709108]

Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
  • 생성 확인

실습

  1. floating ip 할당 -> 2개 -> 인스턴스의 fixed_ip와 연결
  2. output에서는 다음과 같이 출력되어야 한다.

private address
192.168.101.X
192.168.101.Y

public address
211.183.3.X
211.183.3.Y

  • instance.tf
[root@terraform lab2]# vi instance.tf 
  • 아래 코드 추가
resource "openstack_networking_floatingip_v2" "fip" {
	pool = "extnet"
	count = 2
}

resource "openstack_compute_floatingip_associate_v2" "fip" {
	floating_ip = openstack_networking_floatingip_v2.fip.*.address[count.index]
	instance_id = openstack_compute_instance_v2.instance.*.id[count.index]
}

output "private_ip" {
	value = openstack_compute_instance_v2.instance.*.network.0.fixed_ip_v4
}

output "public_ip" {
	value = openstack_networking_floatingip_v2.fip.*.address
}
  • terraform apply
[root@terraform lab2]# terraform apply -auto-approve 
...
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.

Outputs:

private_ip = [
  "192.168.101.206",
  "192.168.101.211",
]
public_ip = [
  "211.183.3.239",
  "211.183.3.203",
]

user_data

vi instance.tf
resource "openstack_compute_instance_v2" "instance" {
        name = "instance-${count.index + 1}"
        image_name = "CentOS7"
        flavor_name = "m1.medium"
        key_pair = "terraformkey"
        security_groups = ["op_httpssh", "icmp"]
        count = 2

        network {
                name = "private1"
        }

        user_data = file("firstboot.sh")
}

user_data를 파일로 추가

  • firstboot.sh
vi firstboot.sh
#!/bin/bash

sudo yum -y install httpd
sudo systemctl start httpd
sudo systemctl enable httpd
echo "<h1>HELLO TERRAFORM</h1>" | sudo tee /var/www/html/index.html

변수를 활용하여 tf 파일 나누기

[root@terraform lab3]# touch provider.tf main.tf floatingip.tf output.tf vars.tf

[root@terraform lab3]# tree
.
├── floatingip.tf
├── main.tf
├── output.tf
├── provider.tf
└── vars.tf

providers.tf

[root@terraform lab3]# cat ../lab2/provider.tf >> provider.tf 

vars.tf

variable "instance" {
	default = {
		image_name = "CentOS7"
		image_id = "5112e14c-3355-459f-8bad-e2881dc838f5"
		count = 1 
	}
}

variable "inside" {
	default = {
		name = "private1"
		id = "24301178-33c1-4c7b-922e-9fd13ea4ec12"		
	}
}

variable "outside" {
	default = {
		name = "extnet"
		id = "98facebd-53fc-4a1c-80be-013026471da4"
	}
}

instance, private, outside 변수 선언. key value 형태의 변수.

floatingip.tf

#################### floating ip ####################
resource "openstack_networking_floatingip_v2" "fip1" {
	pool = var.outside["name"]
	count = var.instance["count"]
}

resource "openstack_compute_floatingip_associate_v2" "fip1" {
	count = var.instance["count"]
	floating_ip = "${openstack_networking_floatingip_v2.fip1[count.index].address}"
	instance_id = "${openstack_compute_instance_v2.instance[count.index].id}"
}

output.tf

output "private_ip" {
	value = openstack_compute_instance_v2.instance.*.network.0.fixed_ip_v4
}

output "public_ip" {
	value = openstack_networking_floatingip_v2.fip1.*.address
}

main.tf

resource "openstack_compute_instance_v2" "instance" {
	name = "instance-${count.index}"
	image_name = var.instance["image_name"]
	flavor_name = "m1.medium"
	key_pair = "terraformkey"
	security_groups = ["webssh", "icmp"]
	count = var.instance["count"]

	network {
		name = var.inside["name"] # private network
	}
}

확인

[root@terraform lab3]# terraform apply -auto-approve 

Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

Outputs:

private_ip = [
  "192.168.101.221",
]
public_ip = [
  "211.183.3.206",
]
profile
take a look

0개의 댓글