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"
}
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.arn 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
}