Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort JSON output from AWS CLI using JMESPath

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.

like image 449
Rohan Kishibe Avatar asked May 19 '26 15:05

Rohan Kishibe


2 Answers

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.

like image 133
Rohan Kishibe Avatar answered May 21 '26 06:05

Rohan Kishibe


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]]"
like image 45
Arun Kamalanathan Avatar answered May 21 '26 07:05

Arun Kamalanathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!