Get the most recent AMI using data source with Terraform

A data source is basically just a query of the AWS API to receive information needed to deploy a resource.

In this case - we need an AMI id based on some filters we're going to provide.

One thing to make sure - is to have the correct owner - so:

  1. Go to the EC2 Console
  2. Click Launch the instance - we will not launch the instance
  3. Search for ubuntu in the OS images and copy AMI id, in my case it is ami-0fb391cce7a602d1f
  4. Go back to EC2 Console and click AMIs under Images
  5. Choose Public Images and put the noted AMI ID there
  6. Copy Owner and AMI NAme, you'll need that - mine is 099720109477 and ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20220609
Start coding in Terraform. Create a file datasources.tf with the following contents:
data "aws_ami" "server_ami" {
  most_recent = true
  owners = ["099720109477"] # put saved owner
  
  filter {
    name = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"] # instead of date put asterisk to get the most recent one
  }
}
Run plan and apply.

To view the details of the AMI run:
terraform state show 'data.aws_ami.server_ami'
Output:
...
    id                    = "ami-0a24ce26f4e187f9a"
    image_id              = "ami-0a24ce26f4e187f9a"
    image_location        = "amazon/ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20220810"
    image_owner_alias     = "amazon"
    image_type            = "machine"
    most_recent           = true
    name                  = "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20220810"
...