Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aws-cli - Filtering output with --query and --filter

Consider I want to query aws cli for an instance list that have the tag:

role=myrole

I want only the InstanceId and that specific tag, so i issue :

~ aws ec2 describe-instances \
    --filter "Name=tag:role,Values=myrole" \
    --query "Reservations[*].Instances[*].[InstanceId,Tags[?Key=='myId'].Value]"

the reply will be :

[
    [
        [
            "i-111111111111111111",
            []
        ]
    ],
    [
        [
            "i-222222222222222222",
            [
                "091117"
            ]
        ]
    ],
    [
        [
            "i-333333333333333333",
            []
        ]
    ]
]

How can i modify the query to get only objects that this tag Value is a non-empty strings ie :

[
    [
        [
            "i-222222222222222222",
            [
                "091117"
            ]
        ]
    ]
]
like image 595
chenchuk Avatar asked Jan 04 '23 11:01

chenchuk


1 Answers

The only piece missing in your command is to ensure that the tag myId is present and has a non-empty value. That filter has to be applied to the selected instances (Instances[*]). How to filter for that is covered in another answer on Stack Overflow and integrating it into your command is rather straight forward:

aws ec2 describe-instances \
  --filter "Name=tag:role,Values=myrole" \
  --query "Reservations[*].Instances[?Tags[?Key=='myId' && Value!='']].[InstanceId,Tags[?Key=='myId'].Value]"
like image 109
Dunedan Avatar answered Jan 13 '23 11:01

Dunedan