Using JMESPath and aws ec2 describe instances to output multiple tag values

牧云@^-^@ 提交于 2020-01-17 07:04:42

问题


I'm trying to output multiple tags from an ec2 instances description. The tag values that I want are Name and aws:autoscaling:groupName.

 "Tags": [
                        {
                            "Value": "somename", 
                            "Key": "Name"
                        }, 
                        {
                            "Value": "some-asg-name", 
                            "Key": "aws:autoscaling:groupName"
                        }, 
                        {
                            "Value": "somethingelse", 
                            "Key": "project"
                        }
                    ], 

Here's what I have so far:

aws ec2 describe-instances --instance-ids i-12345678 --query 'Reservations[].Instances[].[Tags[? contains(`["aws:autoscaling:groupName","Name"]`, Key)] | [0].Value,[1].Value,InstanceId]' --output text

Which results in:

somename       None    i-12345678

Instead of:

somename       some-asg-name    i-12345678

I tried both double pipe || and contains but can't get the output I need. Also, I'm not sure [1].Value is the right way to get the 2nd matching tag.


回答1:


This might be easier to think about if you split filtering your tags and selecting your output into separate pieces.

Step by step:

First, select all instances:

Reservations[].Instances[]

Then pipe to filter for only instances with both of your desired tags:

| [? Tags[? Key == 'Name']] | [? Tags[? Key == 'aws:autoscaling:groupName']]

Then select the InstanceId and tag values:

.[InstanceId,Tags[? Key == 'Name' || Key == 'aws:autoscaling:groupName'].Value]

Full Example:

aws ec2 describe-instances --query "Reservations[].Instances[] | [? Tags[? Key == 'Name']] | [? Tags[? Key == 'aws:autoscaling:groupName']].[InstanceId,Tags[? Key == 'Name' || Key == 'aws:autoscaling:groupName'].Value]"

Example Output

i-aaaa1234
myNameValue myASGvalue
i-bbbb1234
myNameValue myASGvalue

Further Reading

  • AWS Documentation - Controlling Command Output from the AWS Command Line Interface



回答2:


I was thinking about the pipe syntax wrong. This is working:

aws ec2 describe-instances --instance-ids i-12345678 --query 'Reservations[].Instances[].[Tags[?Key==`Name`] | [0].Value,Tags[?Key==`aws:autoscaling:groupName`] | [0].Value,InstanceId]' --output text

and outputs:

somename       some-asg-name    i-12345678

Also, this solution puts the output into one row per instance, so it can be used with many instances in --output table



来源:https://stackoverflow.com/questions/43354116/using-jmespath-and-aws-ec2-describe-instances-to-output-multiple-tag-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!