Terraform v1.0.0 Provider: aws v3.49.0
I created dynamic AWS subnets resources with a for_each from a module.
The resources creation is working fine, however being able to output dynamically created resources is not working and cannot find proper documentation for it.
The subnet module is
resource "aws_subnet" "generic" { vpc_id = var.vpc_id cidr_block = var.cidr_block map_public_ip_on_launch = var.public_ip_on_launch tags = { Name = var.subnet_tag_name Environment = var.subnet_environment } }
With simple module output defined
output "subnet_id" { value = aws_subnet.generic.id }
Then from root module, I am creating a for_each loop over a list variable to create multiple dynamic resources from the module
module "subnets" { source = "../modules/networking/subnet" for_each = var.subnets vpc_id = "vpc-09d6d4c17544f3a49" cidr_block = each.value["cidr_block"] public_ip_on_launch = var.public_ip_on_launch subnet_environment = var.subnet_environment subnet_tag_name = each.value["subnet_tag_name"] }
When I run this without defining outputs in the root module, things get created normally. The problem comes when I try to define the outputs
output "subnets" { value = module.subnets.*.id description = "Imported VPC ID" }
It comes up with this error
│ Error: Unsupported attribute │ │ on output.tf line 2, in output "subnets": │ 2: value = module.subnets.*.id │ │ This object does not have an attribute named "id".
I tried different output definitions. Would appreciate guidance on how to properly define outputs of instances dynamically created with a for_each module.
Per the Terraform documentation , the "splat" operator ( *
) can only be used with lists, and since you're using for_each
your output will be a map.
You need to use map/list comprehension to achieve what you want.
For an output that is a map of key/value pairs (note that I've changed the output description to something that makes more sense):
output "subnets" {
value = {
for k, v in module.subnets:
k => v.subnet_id
}
description = "Subnet IDs"
}
For a list that only contains the subnet IDs:
output "subnets" {
value = [
for k, v in module.subnets:
v.subnet_id
]
description = "Subnet IDs"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.