variable "subnets" {
default = {
"us-east-1a" = "10.1.8.32/28"
"us-east-1b" = "10.1.8.64/28"
"us-east-1c" = "10.1.8.96/28"
}
description = "A map of availability zones and cidr blocks for subnet creation"
}
resource "aws_subnet" "aws_db_subnet" {
for_each = var.subnets
vpc_id = var.vpc_k8s_id
availability_zone = each.key
cidr_block = each.value
tags = {
Product = var.aws_tag_product,
Name = var.aws_tag_name,
Environment = var.aws_tag_env
}
}
resource "aws_db_subnet_group" "aws_db_subnet_group" {
name = "aws-db-subnet-group"
subnet_ids = [for subnet_id in aws_subnet.aws_db_subnet[*]["id"]:subnet_id]
tags = {
Product = var.aws_tag_product,
Name = var.aws_tag_name,
env = var.aws_tag_env
}
}
So if I want to access all the subnetβs ids from the resource β aws_subnet.aws_db_subnet
How do I go about it? I see this error
β·
β Error: Invalid index
β
β on .terraform/modules/aws_rds_db_network/network.tf line 51, in resource "aws_db_subnet_group" "aws_db_subnet_group":
β 51: subnet_ids = [for subnet_id in aws_subnet.aws_db_subnet[*]["id"]:subnet_id]
β
β The given key does not identify an element in this collection value.
Terraform v0.15.4
on darwin_amd64
Syntax would be:
subnet_ids = [for subnet_id in aws_subnet.aws_db_subnet : subnet_id.id]
However terraform might complain about unknown keys when using for_each.
A sample using null_resource:
variable "subnets" {
default = {
"us-east-1a" = "10.1.8.32/28"
"us-east-1b" = "10.1.8.64/28"
"us-east-1c" = "10.1.8.96/28"
}
description = "A map of availability zones and cidr blocks for subnet creation"
}
resource "null_resource" "aws_db_subnet" {
for_each = var.subnets
}
resource "null_resource" "aws_db_subnet_group" {
for_each = {for r,ip in var.subnets : r => null_resource.aws_db_subnet[r].id} # if the latter two are flipped, terraform will complain about an unknown key
}
output "subnetids" {
value = {for r,ip in var.subnets : r => null_resource.aws_db_subnet[r].id}
}
1 Like
Thanks for the reply. I tried what you -
resource "aws_db_subnet_group" "aws_db_subnet_group" {
name = "aws-db-subnet-group"
subnet_ids = {for r,ip in var.subnets : r => aws_subnet.aws_db_subnet[r].id} # if the latter two are flipped, terraform will complain about an unknown key
tags = {
Product = var.aws_tag_product,
Name = var.aws_tag_name,
env = var.aws_tag_env
}
}
I see a new error now.
β·
β Error: Incorrect attribute value type
β
β on .terraform/modules/aws_rds_db_network/network.tf line 51, in resource "aws_db_subnet_group" "aws_db_subnet_group":
β 51: subnet_ids = {for r,ip in var.subnets : r => aws_subnet.aws_db_subnet[r].id} # if the latter two are flipped, terraform will complain about an unknown key
β βββββββββββββββββ
β β aws_subnet.aws_db_subnet is object with 3 attributes
β β var.subnets is object with 3 attributes
β
β Inappropriate value for attribute "subnet_ids": set of string required.
I was too focussed on for_each handling and blind for your question.
subnet_ids = [for r,ip in var.subnets : aws_subnet.aws_db_subnet[r].id]