Hello,
I’m a newbie in terraform and want to realize vpc module with a configuration like shown below.
For now, the output looks like I expected, then I want to iterate over the local variable for creating subnets and all other necessary resources, but I doubt about this approach is correct and not overengineered.
So it would be perfect to hear the opinions from skilled terraformers.
variable "vpcs" {
type = map
default = {
vpc1 = {
cidr = "172.22.0.0/16",
private_subnets = ["172.22.1.0/24", "172.22.2.0/24"],
public_subnets = ["172.22.10.0/24", "172.22.20.0/24"],
tags = {
Name = "app-vpc1",
Environment = "production",
Terraform = "True"
}
},
vpc2 = {
cidr = "172.12.0.0/16",
private_subnets = ["172.12.1.0/24", "172.12.2.0/24"],
public_subnets = ["172.12.10.0/24", "172.12.20.0/24"],
tags = {
Name = "app-vpc2",
Environment = "production",
Terraform = "True"
}
}
}
}
and my module:
variable "vpcs" {
type = map
}
locals {
nestedforeach = [
for vpc_name, vpc_config in var.vpcs: [
for public_subnet in vpc_config.public_subnets: {"${public_subnet}": aws_vpc.this[vpc_name].id}
]
]
}
resource "aws_vpc" "this" {
for_each = var.vpcs
cidr_block = each.value.cidr
instance_tenancy = "default"
enable_dns_support = "true"
enable_dns_hostnames = "true"
enable_classiclink = "false"
tags = each.value.tags
}
output test {
value = flatten(local.nestedforeach)
}
Output:
module.kilda-vpc.aws_vpc.this["vpc1"]: Refreshing state... [id=vpc-082108b97c66df36b]
module.kilda-vpc.aws_vpc.this["vpc2"]: Refreshing state... [id=vpc-0a5a4cbc58f9dc664]
Outputs:
test = [
{
"172.22.10.0/24" = "vpc-082108b97c66df36b"
},
{
"172.22.20.0/24" = "vpc-082108b97c66df36b"
},
{
"172.12.10.0/24" = "vpc-0a5a4cbc58f9dc664"
},
{
"172.12.20.0/24" = "vpc-0a5a4cbc58f9dc664"
},
]