bluethundr
bluethundr

Reputation: 1345

Get Value of Name Tag from EC2 instances using jq

I am trying to get the values of the Name tag of AWS EC2 instances using jq.

aws ec2 describe-instances | jq -r '.Reservations[].Instances[] | .Tags[] | select (.Key == "Name")'

But I am getting this error:

jq: error: Name/0 is not defined at <top-level>, line 1:
.Reservations[].Instances[] | .Tags[] | select (.Key == Name)
jq: 1 compile error

This is the json I'm trying to process:

{
    "Reservations": [{
        "Instances": [{
            "AmiLaunchIndex": 0,
            "ImageId": "ami-00c3c949f325a4149",
            "InstanceId": "i-0c17052ee1c7113e5",
            "Architecture": "x86_64",
            "Tags": [{
                    "Key": "Name",
                    "Value": "bastion001"
                },
                {
                    "Key": "environment",
                    "Value": "stg-us-east"
                }
            ]
        }]
    }]
}

How can I get the value of the Name tag from EC2 instances?

Upvotes: 2

Views: 2793

Answers (3)

krystan honour
krystan honour

Reputation: 6793

You could do something like this, this will get what you want from ec2 in a comma separated list

jq -r '.Reservations[].Instances[] \ | ((.Tags // empty) | from_entries) as $tags | [($tags.Name), ($tags.environment), .ImageId, .InstanceId, .AmiLaunchIndex] | @csv'

The .Tags // empty will ignore those with tags that do not exist if you are wondering.

Hope this helps, it Is correct you do not need jq to get these details, but this is how you do it with :)

Upvotes: 4

peak
peak

Reputation: 116880

There is a mismatch between the jq command-line expression shown in the Q and the error message. I would suggest that, at least until you have sorted things out, you put your jq program in a file, and invoke jq with the -f command-line option.

Upvotes: 1

jellycsc
jellycsc

Reputation: 12359

You don't need extra tools like jq to query the output. AWS CLI has JMESPath built-in to help you do that.

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

Upvotes: 3

Related Questions