Is there a command to list AWS instances that results in short output?
Solution 1:
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:
- AWS CLI Documentation - Controlling Command Output