Contents
Terraform data sources provide information on existing resources. This is handy for configuration dependencies that exist across Terraform plans.
In my scenario, I wanted to attach an Amazon Web Services (AWS) Virtual Private Cloud (VPC) to an existing Transit Gateway. I needed to use a data source to pull the Transit Gateway’s id
value. Using the assigned AWS tags seemed like a viable solution.
Digging In Further
Below is an example of my configuration in AWS:

I could not find a clear description of how to filter a data source by the AWS tag key/value pairs. However, the aws_instance
data source provided me a clue.
The key/value pair can be provided using the syntax below:
- Key: The
name
parameter uses the syntaxtag:<key>
to provide the AWS key name. - Value: The
values
parameter provides the AWS key value.
The full working Terraform code snippet is shown below:
data "aws_ec2_transit_gateway" "tgw" { filter { name = "tag:Name" values = ["wahlnetwork-tgw-prod"] } }
Now that I had the Transit Gateway’s id
value, I was able to supply it to a resource object further along in the plan.
resource "aws_ec2_transit_gateway_vpc_attachment" "vpc-tgw-attachment" {
subnet_ids = [aws_subnet.priv01.id, aws_subnet.priv02.id]
transit_gateway_id = data.aws_ec2_transit_gateway.tgw.id
vpc_id = aws_vpc.vpc.id
}
}
At least now I have written down the filter syntax for an AWS tag for the next time I need it!
Next Steps
Please accept a crisp high five for reaching this point in the post!
If you’d like to learn more about Infrastructure as Code, or other modern technology approaches, head over to the Guided Learning page.