I'm trying to produce an output from a terraform child module which creates a number of subnets based on a variable (which is a map of objects). I create subnets with:
resource "aws_subnet" "this" {
for_each = var.subnets
vpc_id = aws_vpc.vpc.id
availability_zone = each.value.az
cidr_block = each.value.cidr_block
map_public_ip_on_launch = each.value.public
tags = {
Name = each.key
Type = each.value.public ? "public" : "private"
}
}
output.tf in the same folder as the module:
output "vpc_subnets_id" {
description = "The CIDR block of the VPC"
value = values(aws_subnet.this)[*].id
}
output.tf in the main module directory (where main.tf is):
output "vpc_subnets_ids" {
description = "The CIDR block of the VPC"
value = values(module.vpc.aws_subnet.this)[*].id
}
This produces an error:
on output.tf line 17, in output "vpc_subnets_ids":
│ 17: value = values(module.vpc.aws_subnet.this)[*].id
│ ├────────────────
│ │ module.vpc is a object
│
│ This object does not have an attribute named "aws_subnet".
Why doesn't it work, and how to make it work?
Your module output is named vpc_subnets_id
, and not aws_subnet
. It also seems as if your structure query and member accessing is redundant across the two output
. The query and accessing could also potentially fail for an empty var.subnets
, and potentially be unreliable. These fixes all combine as:
# declared module output
output "vpc_subnets_id" {
description = "The CIDR block of the VPC"
value = [for subnet in aws_subnet.this : subnet.id]
}
# root module output
output "vpc_subnets_ids" {
description = "The CIDR block of the VPC"
value = module.vpc.vpc_subnets_id
}