Hi @linuxbsdfreak,
I’m not sure I’m following your example correctly because your first block shows use of a data.aws_vpcs
while your second shows data.aws_subnet
and so I’m not sure how the two are connected. However, I think you are asking how to create one NAT gateway per VPC id in data.aws_vpcs.shoot_vpc_id.ids
, so I’m going to try to answer that here.
My initial instinct would be to do this using resource for_each
where the VPC id is the unique key, which is convenient because the ids
attribute is already a set of strings and so we can just pass it directly to for_each
as long as that data source is able to read during the planning step:
data "aws_nat_gateway" "shoot" {
for_each = data.aws_vpcs.shoot_vpc_id.ids
vpc_id = each.key
tags = {
"Name" = "test-natgw-${each.key}"
}
}
This would declare instances like aws_nat_gateway.shoot["vpc-abc123"]
, assuming you have a VPC with id vpc-abc123
. However, it doesn’t exactly match what you showed in your example because the tagged names here would be like test-natgw-vpc-abc123
. The advantage of this strategy is that if you add a new VPC later then Terraform can just create the new NAT gateway for it without disturbing any of the existing ones.
If you want to assign them names with incrementing integers like you showed in your example then that is possible but will come with an important consequence: if you add a new VPC later which has an id that sorts earlier than one of the existing ones then all of the subsequent VPCs will have their tag names updated to represent their new positions in the sequence, which feels conceptually weird given that VPCs are not really an ordered data type.
With that said, to get that done you’d need to transform that set of id strings into a data structure that has both a name and an index for each one. I’m going to assume we still want Terraform to track the VPCs by their remote ids, and so produce a map from VPC id to index:
data "aws_nat_gateway" "shoot" {
for_each = { for i, id in sort(data.aws_vpcs.shoot_vpc_id.ids) : id => i }
vpc_id = each.key
tags = {
"Name" = "test-natgw-${each.value}"
}
}
Because the for_each
expression now produces a map from VPC id string to index, each.key
inside this block is the VPC id and each.value
is the assigned index. Terraform will still track these objects by their associated VPC id, but will generate the Name
tags based on their position in the sort order.
If you use this variant then I’d encourage you to experiment with applying once with an initial set of VPC ids, and then changing your set of VPC ids by adding and removing elements before running terraform apply
again, and make sure you’re comfortable with the plan Terraform makes in those scenarios, because it’s better to understand the consequences of adding and removing VPCs from your set during development than to get caught out by it once your module is already in production.