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
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.