Good evening,
We have a Terraform configuration that starts with an aws_servicecatalog_provisioned_product
resource to create an EC2 instance. Upon provisioning this resource returns the below outputs (truncated).
outputs = [
{
description = "Amazon Machine Image (AMI) used to create the EC2 instance."
key = "ImageId"
value = "ami-9999"
},
{
description = "The InstanceId of the created EC2 instance."
key = "InstanceId"
value = "i-9999"
},
]
In the same configuration we’re wanting to tag the volumes attached to the instance using aws_ec2_tag
. We understand this is not ideal, but we do not have any influence on the SC product that is provisioning the compute.
How would we go about adding a set of required tags to the instance’s volume(s)? We tried the below, but ran into issues due to our for_each
key using attributes that aren’t known until apply. I expect there is probably an easier solution that I’m missing.
data "aws_ebs_volumes" "this" {
filter {
name = "attachment.instance-id"
values = [for instance in aws_servicecatalog_provisioned_product.this.outputs : instance.value if instance.key == "InstanceID"]
}
}
locals {
required_tags = {
tag1 = var.value1
tag2 = var.value2
managed_by = "Terraform"
}
volume_tags = flatten(
[for vol_id in data.aws_ebs_volumes.this.ids :
[for tag_key, tag_value in local.required_tags : {
vol_id = vol_id,
tag_key = tag_key,
tag_value = tag_value
}
]
])
}
resource "aws_ec2_tag" "this" {
for_each = { for vol_tag in local.volume_tags : "${vol_tag.vol_id}.${vol_tag.tag_key}" => vol_tag }
resource_id = each.value.vol_id
key = each.value.tag_key
value = each.value.tag_value
}
Thank you for your time.