Introduction
This guide demonstrates how to use Terraform to add tags to AWS subnets that were created and are managed outside of the current Terraform configuration.
Procedure
To tag existing subnets, you can first query for them using the aws_subnets data source and then apply tags using the aws_ec2_tag resource with a for_each loop.
The following example configuration demonstrates how to apply a specific key-value tag to all subnets discovered by the data source within a given VPC.
# Use the aws_subnets data source to find existing subnets.
# You can filter by VPC ID or other attributes.
data "aws_subnets" "example" {
filter {
name = "vpc-id"
values = ["vpc-12345678"]
}
}
# Apply a tag to each subnet found by the data source.
resource "aws_ec2_tag" "example" {
for_each = toset(data.aws_subnets.example.ids)
resource_id = each.value
key = "example_key"
value = "example_value"
}Additional Information
Note: If you use
default_tagsin the AWS provider configuration, it may conflict with thisaws_ec2_tagresource when managing the same tags. Ensure your tagging strategy is consistent to avoid potential conflicts.