liveBook · Manning

Aws_ami data source

As explained in Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu

The aws_ami data source is a Terraform AWS provider data source that retrieves an Amazon Machine Image matching specified criteria.

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

How Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu covers it

How deep it goes
Explains read-only lookup, ownership, recency, filters, and missing-match errors, but stops short of provider internals.
Examples
Uses Canonical-owned Ubuntu images filtered by name and HVM virtualization type, alongside default VPC and subnet lookups.
What it assumes
Assumes basic Terraform data-source and AWS resource knowledge while defining filters and lookup arguments concretely.
What you can do after
Configure an AMI lookup that supplies the latest matching image to an EC2 launch.
How it connects
Connects AMI selection to data sources, aws_instance, filtering, Ubuntu, EC2, VPCs, and subnets.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu. The section links point to the parts of the book it draws on.