AWS CLI — Get tags for any object
Here is small goodie. Script to retrieve all tags from any resources in AWS.
I assume that you installed already AWS CLI — let us quick go through.
First you answer questions as
Profile to use
Region to scan
Resource type you want to get tags
echo Please enter profile to use
echo What resource type you want to scan for tags
echo Please enter one of the following
echo customer-gateway \| dedicated-host \| dhcp-options \| elastic-ip \| fleet \| fpga-image \| host-reservation \| image \| instance \| internet-gateway \| key-pair \| launch-template \| natgateway \| network-acl \| network-interface \| placement-group \| reserved-instances \| route-table \| security-group \| snapshot \| spot-instances-request \| subnet \| volume \| vpc \| vpc-endpoint \| vpc-endpoint-service \| vpc-peering-connection \| vpn-connection \| vpn-gateway
Next — script will get all resources in region and filter it against your requested resource.
Note — I choose to continue still querying AWS API in the next step, instead of working with local file, but instead on this step you can save results to file, and work with local json file instead — e.g. remove everything starting with
--filters and leave redirection to file.
echo Gettign Resources RecourceType=$resourceid
aws ec2 describe-tags --filters "Name=resource-type,Values=$resourceid" | jq -r '.Tags| .ResourceId as $d|([$d]|@csv)'|sed 's/\"//g' >resources.txt
Next — script will read resources.txt and will request tags. Again, you will need to change next lines if you prefer to work from your local file
for n in $(cat resources.txt);do (aws ec2 describe-tags --filters "Name=resource-id,Values=$n" --profile $profile --region $region && echo -n $n: >>$region-tags.csv) |jq -r '.Tags|.Key as $k|([$k,.Value]|@csv)'|sed ':a;N;$!ba;s/\n/:/g' >>$region-tags.csv;done
Once done, the CSV file is available in your folder named
Originally published at https://dev.to on September 4, 2020.