Filter Terraform Data Source by AWS Tag

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.

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 syntax tag:<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! I hope this helps you if you found this page while searching for a similar scenario. 🙂