Search code examples
sortingaws-clijmespath

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.


Solution

  • 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.