How to fetch second last AMI ID using AWS CLI

Viewed 323

Using below AWS CLI command, I am able to fetch recently created AMI ID by sorting CreationDate.

aws ec2 describe-images --owners 1234567890 --filters 'Name=name,Values=*AMI*' 'Name=state,Values=available' --output json | jq -r '.Images | sort_by(.CreationDate) | last(.[]).ImageId'

I also wanted to get the second last AMI ID using AWS CLI. Could someone help me out on this?

1 Answers

You can use indices, like in python ([-2]):

aws ec2 describe-images --owners 1234567890 --filters 'Name=name,Values=*AMI*' 'Name=state,Values=available' --output json | jq -r '.Images | sort_by(.CreationDate)[-2].ImageId'
Related