Reputation: 4511
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
Upvotes: 2
Views: 4950
Reputation: 5887
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
Upvotes: 1
Reputation: 1290
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.
Upvotes: 0
Reputation: 5794
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"
Upvotes: 2
Reputation: 45223
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
Upvotes: 2
Reputation: 23492
This is going to be unnecessarily complicated to do in a shell script. Here are some suggestion:
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.AWs-CLI
commands via a perl script and then capture the output in a hash. Perl
is very powerful for handling such data structure.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.
Upvotes: 1
Reputation: 15986
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"
Upvotes: 1