Last active
February 26, 2021 18:15
-
-
Save mrballcb/1d0d4c030f1d00569eaa36dae032106f to your computer and use it in GitHub Desktop.
jq displaying filtered EC2 instances, only selected fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Loops through regions | |
# Gets all data for instances in the inner array | |
# Outputs instance id, AZ, Launch Time, and the Name tag | |
for REGION in us-east-1 us-west-1; do | |
aws --region $REGION ec2 describe-instances | \ | |
jq '.Reservations[].Instances[] | select(.InstanceId as $id | ["id-1234", "id-56789"] | index($id)) | [.InstanceId, .Placement.AvailabilityZone, .LaunchTime, [.Tags[] | select(.Key == "Name") | .Value][] ]' | |
done | |
# I want to comment on and break down the last part of the jq command: | |
# [.InstanceId, .PlacementAvailabilityZone, .Launchtime, [.Tags[] | select(.Key == "Name) | .Value][] ] | |
# That makes it print out something like: | |
# [ | |
# "id-1234", | |
# "us-west-1a", | |
# "2020-02-24T18:03:22.000Z", | |
# "ServerFoo" | |
# ] | |
# | |
# In particular I wanted to break down the odd construction of the last field: | |
# [.Tags[] | select(.Key == "Name") | .Value][] | |
# | |
# The data coming in to this is an array of tag maps, so the ".Tags[]" flattens that array. That's normal usage. | |
# We use "select()" to grab a specific tag, the "Name" tag, and print its value. That's normal usage too. | |
# All of that is in array brackets, which will output these as an array. | |
# But then it's followed by another set of empty brackets. The basic pattern is: | |
# [ something | filter | output ][] | |
# | |
# Why the extra set of brackets? It's the same reason we use ".Tags[]" earlier. | |
# That "output" is an array that looks like this: | |
# [ | |
# "ServerFoo" | |
# ] | |
# | |
# Since I only want the string, not an array with a single string, I also flatten it with an extra set of "[]" at the end. | |
# | |
# The concept I want to stress is that I can flatten an array with "[]" that *I* am creating as part of the output. | |
# When I first tried to do it, I thought there was no way it would work, but it did, and made my life simple. | |
# I use it all the time now, just never documented it anywhere. fin | |
# jq is so so so cool |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jq is just a marvel at its power and capability.