3

I try to sort this output from AWS CLI by ImageId, and I executed command below.

aws ec2 describe-images --profile xxxxxxxxxx \ --filter Name=tag:Name,Values=Backup*some-string* \ --query "Images[*].[Tags[?Key=='Name'].Value[]|[0],ImageId]"

output is:

[
    [
        "Backup-20191215T174530Z-utc-some-string",
        "ami-004"
    ],
    [
        "Backup-20191219T174631Z-utc-some-string",
        "ami-002"
    ],
    [
        "Backup-20191208T174534Z-utc-some-string",
        "ami-001"
    ],
    [
        "Backup-20191222T174530Z-utc-some-string",
        "ami-003"
    ],
    [
        "Backup-20191221T174530Z-utc-some-string",
        "ami-005"
    ]
]

I found sort_by functions of JMESPath could be a solution but that is too hard to understand.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Rohan Kishibe
  • 617
  • 2
  • 10
  • 25

2 Answers2

4
aws ec2 describe-images --profile xxxxxxxxxx \
--filter "Name=tag:Name,Values=Backup*some-string*" \
--query "sort_by(Images[*].[Tags[?Key=='Name'].Value[]|[0],ImageId], &[0])"

or

aws ec2 describe-images --profile xxxxxxxxxx \
--filter "Name=tag:Name,Values=Backup*some-string*" \
--query "Images[*].[Tags[?Key=='Name'].Value[]|[0],ImageId] | sort_by(@, &[0])"

is working fine for me. & (expression type operator) is needed.

Rohan Kishibe
  • 617
  • 2
  • 10
  • 25
1

The idea is, In my solution below, I am sorting the output first by the ImageId and then applying the projections.

aws ec2 describe-images --filter Name=tag:Environment,Values=Staging --output json --query "(sort_by(Images[], &ImageId))[*].[ImageId, Tags[?Key=='Environment'].Value | [0]]"
Arun Kamalanathan
  • 8,107
  • 4
  • 23
  • 39