Reputation: 241
I am using the following to find information about instances associated with a particular Security Group
aws ec2 describe-network-interfaces --filters Name=group-id,Values=sg-123456 --output json
this returns (partial output)
{
"NetworkInterfaces": [
{
"Attachment": {
"AttachTime": "2019-10-09T07:15:44+00:00",
"AttachmentId": "eni-attach-01234567",
"InstanceId": "i-12345678",
"InstanceOwnerId": "123456789",
"Status": "attached"
},
"AvailabilityZone": "us-east-1c",
"Description": "Primary network interface",
"Groups": [
{
"GroupName": "sg-number1",
"GroupId": "sg-123456"
},
{
"GroupName": "sg-number_2",
"GroupId": "sg-654321"
}
],
If I only want to get the instance IDs then I can use a --query and go down the tree
--query 'NetworkInterfaces[*].Attachment.InstanceId'
I can do something similar to get all the SG's as well
--query 'NetworkInterfaces[*].Groups[*].GroupId'
My question is how can I get the InstanceID and the Group.GroupName in one query ?
Or better how do I query multiple attributes when these attributes are on the same level ?
The following did not work:
--query 'NetworkInterfaces[*].Attachment.InstanceId','NetworkInterfaces[*].Groups[*].GroupName'
Upvotes: 6
Views: 2939
Reputation: 39129
You sure can, you will have to use what JMESPath is describing in the examples as filters and multiselect hashes.
With this, you can recreate an object with queries going down the tree.
In your case, with the query:
NetworkInterfaces[*].{
InstanceId: Attachment.InstanceId,
GroupNames: Groups[*].GroupName
}
and the JSON data:
{
"NetworkInterfaces": [
{
"Attachment": {
"AttachTime": "2019-10-09T07:15:44+00:00",
"AttachmentId": "eni-attach-01234567",
"InstanceId": "i-12345678",
"InstanceOwnerId": "123456789",
"Status": "attached"
},
"AvailabilityZone": "us-east-1c",
"Description": "Primary network interface",
"Groups": [
{
"GroupName": "sg-number1",
"GroupId": "sg-123456"
},
{
"GroupName": "sg-number_2",
"GroupId": "sg-654321"
}
]
}
]
}
It gives:
[
{
"InstanceId": "i-12345678",
"GroupNames": [
"sg-number1",
"sg-number_2"
]
}
]
So your commands ends up being:
aws ec2 describe-network-interfaces \
--filters Name=group-id,Values=sg-123456 \
--output json \
--query 'NetworkInterfaces[*].{
InstanceId: Attachment.InstanceId,
GroupNames: Groups[*].GroupName
}'
Upvotes: 5