Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform with aws to select ami based on tag with sort

I'm building a Terraform config and I'm stuck with a tricky ami selection. My CI builds AMIs and add MyVersionTag on it based on the current build of the app on the CI. I would like to select the AMI based on this tag sort by version (X.Y.Z format) to take the latest.

Here is my command line using aws cli to select the AMI I want to use:

aws ec2 describe-images --filters 'Name=tag-key,Values=MyVersionTag' --query 'reverse(sort_by(Images[].{TagValue:Tags|[0].Value,ImageId:ImageId},&TagValue))|[0].ImageId'

I'm searching a way to configure an EC2 instance with this AMI id. I see 2 possible ways (please correct me):

  • aws_instance with pure AMI ID as text (result of a command line through variable)
  • aws_ami with filters

Any idea?

like image 331
brcebn Avatar asked Nov 30 '25 06:11

brcebn


1 Answers

I finally make is using external key word. Here is my solution:

# example.tf

resource "aws_instance" "my-instance" {
  ami = data.external.latest_ami.result.ImageId
  # Other config
}

data "external" "latest_ami" {
  program = ["sh", "latest_ami_id.sh"]
  # Or simply
  program = ["aws", "ec2", "describe-images", "--filters", "Name=tag-key,Values=MyVersionTag", "--query", "reverse(sort_by(Images[].{TagValue:Tags|[0].Value,ImageId:ImageId},&TagValue))|[0].ImageId"]
}

# latest_ami_id.sh

#!/bin/bash

# It returns a json with following keys :
#. ImageId, Description, Tags (version actually)
aws ec2 describe-images --filters "Name=tag-key,Values=SecretCore" --query 'reverse(sort_by(Images[].{TagValue:Tags|[0].Value,ImageId:ImageId},&TagValue))|[0].ImageId'

Hope it will help someone else. 👌🏻

like image 143
brcebn Avatar answered Dec 01 '25 20:12

brcebn