TerraformでEC2インスタンスを作成
Terraformのバージョンは0.13.4。
EC2インスタンスでサーバーごとに異なる設定値を定義
locals {
servers = {
production = {
web01 = {
private_ip = "10.2.1.11"
instance_type = "t3a.micro"
ebs_size = 30
eip_id = "eipalloc-xxxxxxxxxxxxxxxxx"
}
web02 = {
private_ip = "10.2.1.12"
instance_type = "t3a.micro"
ebs_size = 30
eip_id = "eipalloc-yyyyyyyyyyyyyyyyy"
}
}
staging = {
web01 = {(略)}
web02 = {(略)}
}
}
}
EC2インスタンスの作成
for_eachで複数台作成する。
subnet_idはTerraformでAWSのネットワーク設定で作成したもの。
resource "aws_instance" "web" {
for_each = local.servers[terraform.workspace]
ami = "ami-06a46da680048c8ae"
availability_zone = "ap-northeast-1a"
disable_api_termination = false
ebs_optimized = false
get_password_data = false
instance_type = lookup(each.value, "instance_type")
ipv6_address_count = 0
ipv6_addresses = []
key_name = "hoge-aws-ec2"
private_ip = lookup(each.value, "private_ip")
security_groups = []
source_dest_check = true
subnet_id = aws_subnet.public-a.id
tags = {
"Name" = "brassworks"
}
vpc_security_group_ids = [ aws_security_group.web.id ]
timeouts {}
}
EBSの作成とアタッチ
resource "aws_ebs_volume" "web" {
for_each = local.servers[terraform.workspace]
availability_zone = "ap-northeast-1a"
encrypted = false
size = lookup(each.value, "ebs_size")
tags = {
"Name" = "brassworks"
}
type = "gp2"
}
resource "aws_volume_attachment" "web-attachment" {
for_each = local.servers[terraform.workspace]
device_name = "/dev/sdb"
volume_id = aws_ebs_volume.web[each.key].id
instance_id = aws_instance.web[each.key].id
}
Elastic IPの割り当て
TerraformでElastic IP自体を作成することもできるが、ここではAWSコンソールで作成済みのElastic IPを割り当てる。
resource "aws_eip_association" "eip_assoc" {
for_each = local.servers[terraform.workspace]
instance_id = aws_instance.web[each.key].id
allocation_id = lookup(each.value, "eip_id")
}