How to fetch the tags for ec2-describe-instances i

2020-03-06 03:17发布

I want to extract the instance ID and the tags from the result of a command ec2-describe-instances and want to store the result in a text file. The result set gives :

But i want the tags owner and cost.centre also to be fetched Kindly guide me how to do that

6条回答
姐就是有狂的资本
2楼-- · 2020-03-06 03:50

Here is another way to do without using jq and other parsing tools.

ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,Tags[?Key==`Name`].Value | [0],Tags[?Key==`cost.centre`].Value | [0]]' --output text
查看更多
戒情不戒烟
3楼-- · 2020-03-06 03:56

This should work:

aws ec2 describe-instances | jq '.Reservations[].Instances[] | select(contains({Tags: [{Key: "owner"},{Key: "costcenter"}]}))|"Instance ID: \(.InstanceId) Owner: \(.Tags[]|select(.Key=="owner")|.Value), Cost Center: \(.Tags[]|select(.Key=="costcenter")|.Value)"'

TL;DR: The way AWS does tags is a living nightmare, even with jq

Also, use AWS CLI, not old, unsupported tools.

查看更多
疯言疯语
4楼-- · 2020-03-06 04:00

this will help to find instance-id

$ aws ec2 describe-instances --filters Name=vpc-id,Values=vpc-xxx | awk '{ print $8 }' | sort -n | grep "i-"

i-4115d38c

i-5d534697

i-6e679a45

i-7a659851

i-8d6bae40

i-cd6f9000

i-d264ad1e

i-d5888618

i-e2332e2e

ps considering that you already configured / run "aws configure"

查看更多
The star\"
5楼-- · 2020-03-06 04:01

If I understand the question correctly, I think you just need to add expressions to your 2nd grep:

ec2-describe-instances | grep -i "tag" | grep -i -e "name" -e "owner" -e "cost.centre"
查看更多
可以哭但决不认输i
6楼-- · 2020-03-06 04:13

This is going to be unnecessarily complicated to do in a shell script. Here are some suggestion:

  1. you are using ec2cli. Don't use that. Use AWS-CLI instead. Because parsing the output in ec2cli is a pain. Whereas AWS-CLI provides output in JSON, it is way more easier to parse. Also, AWS is going to support AWS-CLI only henceforth.
  2. The information that you need a perfect use-case for using a hash. You can either install and run AWs-CLI commands via a perl script and then capture the output in a hash. Perl is very powerful for handling such data structure.
  3. OR, you can use one of the SDKs from AWS (I use Ruby SDK) and then capture the whole information in a hash and then print it the way you want.

Bottom line is, you need to capture the tags in a hash to make your life easier. Ans this becomes more and more prominent when you have multiple tags.

查看更多
女痞
7楼-- · 2020-03-06 04:14

Using awk

ec2-describe-instances |awk 'BEGIN{IGNORECASE=1}/(name|owner|cost.center)/&&/tag/'

TAG instance    i-c4    Name    Rii_Win_SAML
TAG instance    i-c42   Owner   Rii Pandey
查看更多
登录 后发表回答