I am trying to dynamically create some aws resources in terraform making use of count and then build an output variable containing a list of all created resource ids
resource "aws_subnet" "subnet-1" {
// If subnet_id value is supplied then we set count to 1 to create otherwise skip
count = "${replace(replace(var.primary_subnet_cidr, "/^.+/", "1"), "/^$/", "0")}"
tags = {
Name = "subnet-1"
}
cidr_block = "${var.primary_subnet_cidr}"
vpc_id = "${var.vpc_id}"
availability_zone = "${var.aws_region}a"
}
resource "aws_subnet" "subnet-2" {
// If subnet_id value is supplied then we set count to 1 to create otherwise skip
count = "${replace(replace(var.secondary_subnet_cidr, "/^.+/", "1"),"/^$/", "0")}"
tags = {
Name = "subnet-2"
}
cidr_block = "${var.secondary_subnet_cidr}"
vpc_id = "${var.vpc_id}"
availability_zone = "${var.aws_region}b"
}
output "ids" {
value = ["${aws_subnet.subnet-1.id}","${aws_subnet.subnet-2.id}"]
}
The idea is to create only the subnet you want by supplying its variable (primary_subnet_cidr or secondary_subnet_cidr).
Creating them dynamically works fine however my issue is with the dynamic list.
When attempting to use this list in something like a aws_db_subnet_group.subnet_ids
which takes in a list, it only works if both subnets have been created otherwise it throws me the following error
InvalidSubnet: Subnet IDs are required.
I have also tried this
output "ids" {
value = ["${aws_subnet.*.id}"]
}
But terraform does not seem to support wildcards on resource level.
I suspect this has to do with the way I generated the output list. Is there a better way to generate that dynamic list so it includes only the created resources?