I’m trying to get the launch template VersionNumber based on the deployment_version tag.
aws ec2 describe-launch-template-versions --launch-template-id lt-1234
Will return something like
{
"LaunchTemplateVersions": [
{
"LaunchTemplateId": "lt-1234",
"LaunchTemplateName": "api",
"VersionNumber": 16,
"LaunchTemplateData": {
"TagSpecifications": [
{
"ResourceType": "instance",
"Tags": [
{
"Key": "deployment_version",
"Value": "release/6.1"
},
{
"Key": "server_type",
"Value": "api"
}
]
}
]
}
},
{
"LaunchTemplateId": "lt-1234",
"LaunchTemplateName": "api",
"VersionNumber": 15,
"LaunchTemplateData": {
"TagSpecifications": [
{
"ResourceType": "instance",
"Tags": [
{
"Key": "deployment_version",
"Value": "release/5.7"
},
{
"Key": "server_type",
"Value": "api"
}
]
}
]
}
}
]
}
I tried using jq building something like this
aws ec2 describe-launch-template-versions --launch-template-id lt-1234 | jq '.LaunchTemplateVersions[] | select(.LaunchTemplateData.TagSpecifications.Tags[].Value=="release/6.1")'
But it doesn’t work, with error:
jq: error (at <stdin>:848): Cannot index array with string "Tags"
Most of the jq select examples I could find were made for single level object, does anyone know how to return VersionNumber (16) baes on the tag value (release/6.1) using the example data from above?
2
Answers
It’s unclear what you want to happen when there are several elements in the
TagSpecifications
array (I assume there can be different resource types). If you want to get a stream of all version numbers if any tag specification matches, you could use the following, leveraging the fact that theTags
array can be converted to an object:to_entries
will convert arrays such as[{"Key":"a", "Value":1}, {"Key":"b", "Value":2}]
into objects ({"a":1, "b":2}
for this example).If you are only interested in the first tag, the
select
becomes:Since your sample input only contains a single specification, the output is the same for both:
If you need valid JSON as output, you have to produce an array. To do that, replace the pattern
.x[] | select(f) | g
with.x | map(select(f) | g)
. This should output[16]
.But there might be other solutions that are a better fit for you. Maybe you are only interested in tag specifications of type "instance" (and there will be only a single item with that type)?