How to Filter Data Source Results in Terraform Easily
In Terraform, you filter data source results by using the
filter block or specific filter arguments inside the data source configuration. This lets you narrow down the returned resources based on key-value pairs, making your infrastructure queries precise and efficient.Syntax
The filter block inside a Terraform data source lets you specify conditions to narrow down results. It usually contains name and values fields. The name is the attribute to filter by, and values is a list of acceptable values for that attribute.
Some data sources also support direct filter arguments like tags or ids for filtering.
terraform
data "aws_ami" "example" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-gp2"] } filter { name = "virtualization-type" values = ["hvm"] } }
Example
This example shows how to filter AWS AMIs to get the most recent Amazon Linux 2 AMI with HVM virtualization. The filter blocks specify the AMI name pattern and virtualization type.
terraform
provider "aws" { region = "us-east-1" } data "aws_ami" "amazon_linux" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-gp2"] } filter { name = "virtualization-type" values = ["hvm"] } } output "ami_id" { value = data.aws_ami.amazon_linux.id }
Output
ami_id = "ami-0abcdef1234567890"
Common Pitfalls
- Using incorrect attribute names in
filter.namecauses no results or errors. - Not using lists for
valuesleads to syntax errors. - Expecting filters to work on unsupported data sources or attributes.
- Forgetting to set
most_recentwhen expecting the latest resource.
terraform
data "aws_ami" "wrong" { owners = ["amazon"] filter { name = "wrong-attribute" values = ["value"] } } # Correct way: data "aws_ami" "correct" { owners = ["amazon"] filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-gp2"] } }
Quick Reference
| Field | Description | Example |
|---|---|---|
| filter.name | Attribute to filter by | "name" |
| filter.values | List of values to match | ["amzn2-ami-hvm-*-x86_64-gp2"] |
| most_recent | Return the latest matching resource | true |
| owners | Filter by resource owner | ["amazon"] |
Key Takeaways
Use the filter block with name and values to narrow data source results.
Always provide values as a list, even if it has one item.
Check the data source documentation for supported filter attributes.
Use most_recent to get the latest matching resource when needed.
Incorrect filter names or formats cause no results or errors.