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
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"
This is going to be unnecessarily complicated to do in a shell script. Here are some suggestion:
- 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.
- 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.
- 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.
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
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"
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
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.