chenchuk
chenchuk

Reputation: 5742

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"
            ]
        ]
    ]
]

Upvotes: 4

Views: 9296

Answers (1)

Dunedan
Dunedan

Reputation: 8435

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]"

Upvotes: 9

Related Questions