なぜ作った
呼び出し元のmain.tfの可読性を保ちつつ、モジュール側でよしなにサブネット作って欲しかった。
コード
main.tf
module mo_subnet {
source = "./modules/subnet"
vpc_id = module.mo_vpc.id
subnets = [
{
name = "3net"
cidr_block = cidrsubnet(var.cidr, 8, 0)
availability_zone = "ap-northeast-1a"
},
{
name = "5net"
cidr_block = "10.0.5.0/24"
availability_zone = "ap-northeast-1c"
}
]
}a
./modules/subnet/main.tf
variable "vpc_id" {
type = string
}
variable "subnets" {
type = list
}
resource aws_subnet this {
count = length(var.subnets)
vpc_id = var.vpc_id
# インスタンスにパブリックIPアドレスを自動的に割り当てるのを防止
map_public_ip_on_launch = false
cidr_block = var.subnets[count.index].cidr_block
availability_zone = var.subnets[count.index].availability_zone
tags = {
Name = var.subnets[count.index].name
}
}
参考
-https://www.hashicorp.com/blog/hashicorp-terraform-0-12-preview-for-and-for-each