Terraform Tutorial — Filtering Data Sources
Most AWS data sources support filter blocks. Filters narrow results using the same filter names as the AWS CLI and API.
filter Block Syntax
filter {
name = "FILTER_NAME"
values = ["VALUE1", "VALUE2"]
}
name: The filter name from AWS API docsvalues: A list of acceptable values (OR logic within a filter)- Multiple
filterblocks use AND logic
Combining Filters (AND Logic)
Find Ubuntu 22.04 AMIs that are HVM and EBS-backed:
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
filter {
name = "root-device-type"
values = ["ebs"]
}
}
All three filters must match (AND).
Multiple Values (OR Logic)
Find subnets in either AZ:
data "aws_subnets" "public" {
filter {
name = "vpc-id"
values = [aws_vpc.main.id]
}
filter {
name = "availability-zone"
values = ["us-east-1a", "us-east-1b"] # either AZ matches
}
}
most_recent Flag
When multiple AMIs match, most_recent = true picks the newest:
data "aws_ami" "amazon_linux" {
most_recent = true # ← picks the latest match
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}
}
Without most_recent, Terraform fails if multiple AMIs match.
Tag-Based Filtering
Find resources by tags:
data "aws_vpc" "production" {
filter {
name = "tag:Environment"
values = ["production"]
}
filter {
name = "tag:Team"
values = ["platform"]
}
}
Finding Filter Names
Filter names come from the AWS API. Find them in:
- Terraform Registry docs: Each data source lists supported filters
- AWS CLI:
aws ec2 describe-images helpshows available filters - AWS API Reference: DescribeInstances, DescribeVpcs, etc.
What’s Next?
Let’s see how to combine data sources with resources for powerful patterns.
← AWS Data Source Examples Combining Data Sources with Resources →