terraform: Get the latest AMI id

Terraform AWS AMI datasource latest

2 min read | by Jordi Prats

Hard coding values is never a good idea, using the aws_ami datasource we can query AWS to fetch the latest AMI available, or any AMI really, as long as we properly set the filters so than just one AMI is selected.

To do so we just need to filter the images we want to retrieve using it's name, architecture... (or any other properly), it's owner and finally instruct terraform to get the most recent using the most_recent option, for example:

data "aws_ami" "amazon2" {
  most_recent = true

  filter {
    name = "name"
    values = ["amzn2-ami-*-hvm-*-arm64-gp2"]
  }

  filter {
    name = "architecture"
    values = ["arm64"]
  }

  owners = ["amazon"]
}

Using this code we are retrieving the most recent AMI that it's name matches amzn2-ami-*-hvm-*-arm64-gp2 using arm64 architecture that's owned by amazon

To get the full reference of available filters we can check the AWS CLI documentation about describe-images.


Posted on 06/04/2022