Centered image

Querying the AWS API for the latest AMIs

This is a great time saver, it stops you from having to hard code any AMI IDs within Terraform. This solution will also enable you to get the latest AMIs in the region you’re working in by dynamically querying the AWS API. Good stuff!

Getting latest Ubuntu AMI with Terraform

First our provider block

provider "aws" {
    region = "eu-west-1" # Ireland region, change as you wish
    access_key = "1234567890"
    secret_key = "1234567890"
}

Now lets define our instance

resource "aws_instance" "my_first_instance" {
    ami           = "${data.aws_ami.latest-ubuntu.id}"
    instance_type = "t2.micro"
}

And now lets query the AWS API for the latest Ubuntu Xenial AMI

data "aws_ami" "latest-ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical

  filter {
      name   = "name"
      values = ["ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-*"]
  }

  filter {
      name   = "virtualization-type"
      values = ["hvm"]
  }
}

Now all you have to do is run terraform init to download the AWS provider, then terraform plan to check your code and finally terraform apply to make it live.

If you are intrested in CentOS 7 or use AWS ECS AMIs the code for them is just below

Latest ECS AMI with Terraform

data "aws_ami" "latest_ecs" {
most_recent = true
owners = ["591542846629"] # AWS

  filter {
      name   = "name"
      values = ["*amazon-ecs-optimized"]
  }

  filter {
      name   = "virtualization-type"
      values = ["hvm"]
  }  
}

Latest CentOS 7 AMI with Terraform

data "aws_ami" "centos" {
owners      = ["679593333241"]
most_recent = true

  filter {
      name   = "name"
      values = ["CentOS Linux 7 x86_64 HVM EBS *"]
  }

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

  filter {
      name   = "root-device-type"
      values = ["ebs"]
  }
}

Hopefully this will save you some time!