Use the aws_ami data source when an EC2 configuration needs a suitable Amazon Machine Image without hardcoding an image ID. It performs a read-only lookup and exposes the matching AMI for reuse by Terraform resources. section 2.1.4
The lookup combines an owner account, most_recent, and filter blocks. owners restricts results to a publisher, most_recent selects the newest published match, and filters narrow the result by attributes such as image name and virtualization type. section 2.1.4 section 2.6
Listing 2.2 Using Terraform to look up data
data "aws_vpc" "default" { #1
default = true
}
data "aws_subnets" "default" {
filter { #2
name = "vpc-id"
values = [data.aws_vpc.default.id] #3
}
}
data "aws_ami" "ubuntu" {
owners = ["099720109477"] #4
most_recent = true
filter { #5
name = "virtualization-type"
values = ["hvm"]
}
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
}
This configuration shows an AMI lookup alongside VPC and subnet discovery, including publisher ownership, latest-image selection, and multiple filters. section 2.1.4
Apply the data source with these operational expectations:
- Reference the resulting AMI value from an aws_instance or another resource that launches infrastructure. section 2.6
- Treat most_recent = true as dynamic behavior: a newly published matching image can change the lookup result and provide newer fixes and security patches. section 2.1.4
- Expect planning to fail when aws_ami finds no matching image; unlike collection-oriented lookups, it does not normally return an empty result. section 2.6
