Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I combine multiple attributes from different nodes of an AWS cli result?

I have a JSON response from an AWS CLI command that looks like this:

[
    {
        "AmiLaunchIndex": 0,
        "ImageId": "ami-03ededff12e34e59e",
        "InstanceId": "i-01e625ed10dadda91",
        "InstanceType": "t2.micro",
        "LaunchTime": "2022-04-18T02:35:03+00:00",
        "Monitoring": {
            "State": "disabled"
        },
        "Tags": [
            {
                "Key": "Name",
                "Value": "Some Server"
            }
        ]
    }
]

How do I extract the Instance ID and the Tag Name so that it prints like this:

Instance ID: i-01e625ed10dadda91
Name: Some Server

So far I’ve tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

jq '.[] | "Instance ID: \(.InstanceId) 
Tag Name: \(.Tags[0].Value)"'

But it will break as soon as there are multiple tags or when the tag don’t exist.

>Solution :

If you want to join multiple tags together and produce as a single result, combine them together in a CSV format like below

jq --raw-output '.[] | 
  "Instance ID: \(.InstanceId)\nTag Name: \( .Tags | map(select(.Key == "Name").Value) |join(","))"'

Note the inclusion of \n character inside the interpolated string sequence which expands into the newline when printed in raw output mode.

jqplay demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading