How can I supply multiple values to the subnet_ids
attribute as below?
resource "aws_subnet" "db_subnet" {
for_each = var.db_subnet_cidrs
vpc_id = aws_vpc.default.id
availability_zone = each.key
cidr_block = each.value
}
resource "aws_db_subnet_group" "default" {
name = "default-subnet-group"
subnet_ids = ["aws_subnet.db_subnet.*.id"]
tags = {
Name = "database-subnet-group"
}
}
The subnets are being created correctly but the subnet group isn't. When I apply
this I get the following error:
Error: Error creating DB Subnet Group: InvalidParameterValue: Some input subnets in :[aws_subnet.db_subnet.*.id] are invalid.
status code: 400, request id: 0b68518f-e229-4f57-bf68-4ba46c1c75c2
Your current code is trying to set the subnet IDs of the DB subnet group equal to a string literal of aws_subnet.db_subnet.*.id
which is obviously not a valid subnet identifier. Normally Terraform would warn you that it doesn't match a subnet ID format (eg subnet-1234abcd
) but it looks like the aws_db_subnet_group
resource doesn't currently validate this .
Secondly, the way you're trying to use the output of a for_each
looped resource also won't work. If you were using count
to loop over your subnets that you are creating then you'd have something like the following:
resource "aws_subnet" "db_subnet" {
count = length(var.db_subnet_cidrs)
vpc_id = aws_vpc.default.id
availability_zone = count.index
cidr_block = var.db_subnet_cidrs[count.index]
}
resource "aws_db_subnet_group" "default" {
name = "default-subnet-group"
subnet_ids = aws_subnet.db_subnet.*.id
tags = {
Name = "database-subnet-group"
}
}
The count
looped resources have a splat operator output that has all of the outputs as a list already so you can pass that directly to the aws_db_subnet_group
resource.
But if you want to use for_each
to loop over things then you currently need to use a slightly different syntax to get at the values from the looped resource:
resource "aws_subnet" "db_subnet" {
for_each = var.db_subnet_cidrs
vpc_id = aws_vpc.default.id
availability_zone = each.key
cidr_block = each.value
}
resource "aws_db_subnet_group" "default" {
name = "default-subnet-group"
subnet_ids = values(aws_subnet.db_subnet)[*].id
tags = {
Name = "database-subnet-group"
}
}
This will extract the values of the looped aws_subnet
resource, grabs all of them and then uses just the id
attribute from the resource. The use of the splat operator again creates a list that you can pass directly to the subnet_ids
parameter in the aws_db_subnet
resource.
I was also encountering the same error. my architecture design included a single VPC with 2 subnets. These 2 subnets were in same availability zone [us-east-1a]
. to overcome the aforementioned error, I simply changed the AZs of and subnets [us-east-1a][us-east-1b]
and BOOM! It worked
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.