3

I have my AWS CLI set up and can use aws ec2 describe-instances to get the json object returned that describes all the known details of my instances. Is there an easy way to get just a short list, like instance name and instance id?

I want to be able to work with my instances on the command-line, but to get the instance ids (which commands like start-instances require), I have to scroll through all that output.

2

Yes, via the --query option.

This option allows you to filter down and return specific elements from the structure. There is a special wildcard [*] notation that allows you to iterate over lists of objects; we'll use this to iterate over the list of EC2 instances and return your desired values.

Retrieving InstanceID, Instance Tag Name as JSON:

aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Tags[?Key==`Name`].Value | [0]]'

[
    [
        [
            "i-abcd1234",
            "MyFirstInstance"
        ]
    ],
    [
        [
            "i-efgh5678",
            "MySecondInstance"
        ]
    ]
]

Retrieving InstanceID, Instance Tag Name as Text:

If you don't want to work with json, you can also add the --output option to output text:

aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Tags[?Key==`Name`].Value | [0]]' --output text

i-abcd1234      MyFirstInstance
i-efgh5678      MySecondInstance

Further reading:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.