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
you can do that using a python code in an external resource:
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
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