I’ve created subnets in one AWS account and shared them with another AWS account.
I’m using the following Terraform code to get the individual subnet info:
data "aws_subnets" "subnets" {
filter {
name = "vpc-id"
values = [var.vpc_id]
}
}
data "aws_subnet" "subnet" {
for_each = toset(data.aws_subnets.subnets.ids)
id = each.value
}
data.aws_subnet.subnet
is a collection of all of the subnets with all of their information within. I want to use this to generate an aws_ec2_tag for each tag on each subnet. The purpose of this is to ensure that tags are the same between the source AWS account and the AWS account that I’m sharing the subnets with.
I’ve got this so far, but I’m running up against a wall:
resource "aws_ec2_tag" "subnet_tags" {
provider = aws.dst
for_each = {
for subnet_id, subnet in data.aws_subnet.subnet : subnet_id => {
for tag_key, tag_value in subnet.tags : tag_key => tag_value
}
}
resource_id = data.aws_subnet.subnet[each.key].id
key = each.key
value = each.value
}
I’m getting the following error:
╷
│ Error: Incorrect attribute value type
│
│ on main.tf line 52, in resource "aws_ec2_tag" "subnet_tags":
│ 52: value = each.value
│ ├────────────────
│ │ each.value is object with 7 attributes
│
│ Inappropriate value for attribute "value": string required.
Please help me recreate my tags for the shared subnets. Thanks!
2
Answers
I ended up chaining locals to get what I needed. I needed a unique key for each subnet/tag map for the for_each loop. It's not an elegant solution, but it works without any major changes to my module.
NOTE that with the same provider you'd just be duplicating tags for the same resources. I'm using a separate provider for the AWS account that I'm sharing the subnets with, hence
provider = aws.dst
.Your Data
You need to understand your data before you use it …
best you can do is use some outputs:
In my test if we do a TF plan on that we get:
that is not something you can use in the aws_ec2_tag
Combine Tags
So the first thing we need to do is combine all those tags…
I’m going to use a couple of terraform functions:
values
https://developer.hashicorp.com/terraform/language/functions/valuesmerge
https://developer.hashicorp.com/terraform/language/functions/mergethat will give a unique list of all tags:
Loops
The next problem you have is that there is a list of subnets and also a list of unique tags, but the
resource "aws_ec2_tag"
can create only one at a time, so we can use a module for that:that way we are looping over all subnets…
inside that module we need to do a couple of things:
setsubtract
is the function to use, but it expects parameters as specific data type so we need to do some intermediary conversionsFull Code
https://github.com/heldersepu/hs-scripts/tree/master/TerraForm/aws_subnet_tags