skip to Main Content

I use the following Terraform code snippet to fetch the latest image. However, I have a requirement: the image must be 7 days old. If the latest image is not 7 days old, I must fetch the previous image.

How to do that?

  recipe = {
    description       = "description"
    parent_image_arn  = "arn:aws:imagebuilder:us-east-1:aws:image/amazon-linux-2-x86/x.x.x"
    working_directory = "/tmp"
  }

2

Answers


  1. you can do that using a python code in an external resource:

    data "external" "image_arn" {
      program = ["python3", "filter_image.py"]
    }
    

    the filter_image.py will check all the images, order them by date, if the newest one is not older than 7 days, it will return for you the previous one, for example like this return {"image_arn": eligible_images[0]['arn']}

    then you can easily access the arn using the data resource

    output "image_arn" {
      value = data.external.image_arn.result["image_arn"]
    }
    
    Login or Signup to reply.
  2. You can use data blocks to look up AMI’s that meet your criteria. This works by setting the before date as 7 days before now. Then searching for a list of AMI’s using a filter and returning then in creation date order.

    We then look up the details for each AMI. We compare the creation date for each AMI to the before date we are interested in and keep only those that are before our date.

    Since this is a sorted list by date we can take the first item which will be the latest date which is before the date we specified

    locals {
      # Set the date as 7 days ago
      ami_before_date = timeadd(timestamp(), "-168h") 
    
      # Loop through all the AMI's and return only those with a creation date before ours
      valid_amis = [for ami in data.aws_ami.ami_data: ami.id if timecmp(ami.creation_date, local.ami_before_date) == -1]
    
      # Since this is a sorted list the first item is the latest valid ami
      latest_ami_before_date = local.valid_amis[0]
    }
    
    # Get all AMI's that meet our criteria
    data "aws_ami_ids" "potential_amis" {
      owners = ["123456789012"]
      filter {
        name = "name"
        values = ["*Windows_Server-2022-English-Full-Base*"]
      }
      sort_ascending = true
    }
    
    # Lookup the details of each AMI
    data "aws_ami" "ami_data" {
      count = length(data.aws_ami_ids.potential_amis.ids)
      filter {
        name = "image-id"
        values = [data.aws_ami_ids.potential_amis.ids[count.index]]
      }
    }
    
    output "latest_ami_before_date" {
      value = local.latest_ami_before_date
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search