Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
bluethundr Avatar asked Jan 17 '26 21:01

bluethundr


1 Answers

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 :)

like image 137
krystan honour Avatar answered Jan 20 '26 22:01

krystan honour