Wednesday, May 2, 2018

How to use the aws cli and jq to list instance id and name tag


Using the Amazon Web Services CLI (command line interpreter tool), you can get information about virtual machines (EC2s). The information is JSON format, but it is quite voluminous. If you just want to see the two fields of Instance Id and the Name tag, it can be a challenge because the tags consist of an array of tag names paired with tag values. So, the magic here is the jq code necessary to grab the right tag.

# build up the jq code in two parts
jqProgram1='.Reservations[].Instances[] | (.Tags | '
jqProgram2='from_entries) as $tags | .InstanceId + ", " + $tags.Name'
jqProgram="$jqProgram1 $jqProgram2"

aws --profile myprofile --region us-east-1 ec2 describe-instances \
   --filters Name=tag-key,Values=Name |   \
   jq "$jqProgram" 
Example output:
"i-0f5f9271233816c3f, instance-name-1"
"i-0bd45657eefdb0345, instance-name-2"
"i-00fab46ea64a78997, instance-name-3"
The jq program captures the values of each tag as the variable tags which then has a .Name field to represent the Name tag.