Terraform Tutorial — Filtering Data Sources

1 minute read

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 docs
  • values: A list of acceptable values (OR logic within a filter)
  • Multiple filter blocks 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:

  1. Terraform Registry docs: Each data source lists supported filters
  2. AWS CLI: aws ec2 describe-images help shows available filters
  3. 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 →