Home > front end >  jq is not printing the lines where select() returns null
jq is not printing the lines where select() returns null

Time:12-23

I am trying to fetch all the ec2 instances from AWS using awscli with Tag Name.
command I used is

aws ec2 describe-instances | \
jq -r '.Reservations[].Instances[] | (.Tags[] | select(.Key == "Name") | .Value)   " " \
  .InstanceId   " "   .InstanceType   " "   .KeyName   " "   .PrivateIpAddress   " "   .PublicIpAddress'

Here, jq is printing the instances only with tag Name, and other instances which don't have tag name are not printed.
am I using the select() in wrong way?

Actual output:

master-bastion i-026b52da57ae3a85 t2.micro aus 10.90.0.68 52.62.76.17
master-mongodb_1 i-083bceea3aea1832 t3.medium aus 10.90.100.25
master-mongo i-06d669ba5cda0c74 t3.medium aus 10.90.100.12
master-solr1 i-09752d54fe143fec t2.medium aus 10.90.100.12
master-solr2 i-039bf2028ec15d97 t2.medium aus 10.90.101.22
master-solr3 i-09fc04ceeeb1efae t2.medium aus 10.90.100.6
rabbitmq-1 i-0125de65ba60627a t2.small aus 10.90.100.10
rabbitmq-2 i-069d546deb4a1c23 t2.small aus 10.90.101.11

Expected Output:

master-bastion i-026b52da57ae3a85 t2.micro aus 10.90.0.68 52.62.76.17
i-06d669ba5cda0c4d t3.medium aus 10.90.100.142
i-062669ba5cda0sfs t3.medium aus 10.90.100.147
master-mongodb_1 i-083bceea3aea1832 t3.medium aus 10.90.100.25
master-mongo i-06d669ba5cda0c74 t3.medium aus 10.90.100.12
master-solr1 i-09752d54fe143fec t2.medium aus 10.90.100.12
master-solr2 i-039bf2028ec15d97 t2.medium aus 10.90.101.22
master-solr3 i-09fc04ceeeb1efae t2.medium aus 10.90.100.6
rabbitmq-1 i-0125de65ba60627a t2.small aus 10.90.100.10
rabbitmq-2 i-069d546deb4a1c23 t2.small aus 10.90.101.11

CodePudding user response:

If we focus on just the tags, I see two solutions:

(.Tags[] | select(.Key == "Name")).value // ""

This uses the // operator to return "" in case the .value does not exist.

Alternatively, you can shoehorn the tags into an object first:

.Tags | map({key: .Key, value: .Value}) | from_entries | .Name // ""
  • Related