问题
I'm trying to go through an array of objects w/ jq and convert that to csv. I can do the some of the selection and to csv part but what I'm struggling with is figuring out how to get the Name
tag value of each object.
The json looks like this:
{
"Groups": [],
"Instances": [
{
"InstanceType": "m5.xlarge",
"Tags": [
{
"Key": "jenkins_slave_type",
"Value": "demand_ec2 small"
},
{
"Key": "color",
"Value": "jenkins"
},
{
"Key": "role",
"Value": "jenkins"
},
{
"Key": "stack",
"Value": "dev-us-east-1"
},
{
"Key": "Name",
"Value": "worker-jenkins"
},
{
"Key": "secondary-role",
"Value": "worker"
}
],
"VirtualizationType": "hvm",
"CpuOptions": {
"CoreCount": 2,
"ThreadsPerCore": 2
},
"CapacityReservationSpecification": {
"CapacityReservationPreference": "open"
},
"HibernationOptions": {
"Configured": false
},
"MetadataOptions": {
"State": "applied",
"HttpTokens": "optional",
"HttpPutResponseHopLimit": 1,
"HttpEndpoint": "enabled"
}
}
]
}
{
"Groups": [],
"Instances": [
{
"InstanceType": "t2.micro",
"Tags": [
{
"Key": "Description",
"Value": "test"
},
{
"Key": "Name",
"Value": "test-connection-cloud-sql"
}
],
"VirtualizationType": "hvm",
"CpuOptions": {
"CoreCount": 1,
"ThreadsPerCore": 1
},
"CapacityReservationSpecification": {
"CapacityReservationPreference": "open"
},
"HibernationOptions": {
"Configured": false
},
"MetadataOptions": {
"State": "applied",
"HttpTokens": "optional",
"HttpPutResponseHopLimit": 1,
"HttpEndpoint": "enabled"
}
}
]
}
I can get to the instance type like this:
aws ec2 describe-instances | jq '.Reservations[] | {type: .Instances[].InstanceType}'
but I can't seem to get to the Name
value in Tags
thats not nested. I've done it this way but its still nested:
aws ec2 describe-instances | jq '.Reservations[] | {type: .Instances[].InstanceType, name: .Instances[].Tags[] | select (.Key == "Name")}'
回答1:
Expand Instances
once to avoid a combinatorial explosion. To apply a filter to the result(s) of select
, simply write the filter next to it.
.Reservations[].Instances[] | {InstanceType, name: .Tags[] | select(.Key == "Name") .Value}
Online demo
来源:https://stackoverflow.com/questions/62519154/pair-values-from-different-levels-selecting-one-based-on-neighbor-member