Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query EC2 tags from within instance

Amazon recently added the wonderful feature of tagging EC2 instances with key-value pairs to make management of large numbers of VMs a bit easier.

Is there some way to query these tags in the same way as some of the other user-set data? For example:

$ curl http://169.254.169.254/latest/meta-data/placement/availability-zone us-east-1d 

Is there some similar way to query the tags?

like image 365
Josh Lindsey Avatar asked Oct 07 '10 15:10

Josh Lindsey


People also ask

How do I find my EC2 instance tags?

To get started, you can enable tags on instance metadata at launch in the console or CLI and you can save this launch setting in a launch template. You can also use the CLI to enable tags on instance metadata on a running instance or on a stopped instance.

How do I find the instance metadata on an EC2 instance?

To view instance metadata, you can only use the link-local address of 169.254. 169.254 to access. Requests to the metadata via the URI are free, so there are no additional charges from AWS. Using the curl tool on Linux or the PowerShell cmdlet Invoke-WebRequest on Windows, you will first create your token.

What URL can be used to view all categories of instance metadata from within a running instance?

To view all categories of instance metadata from within a running instance, use the following IPv4 or IPv6 URIs. The IP addresses are link-local addresses and are valid only from the instance. For more information, see Link-local address on Wikipedia.

What is EC2 instance metadata?

Instance metadata is data about your instance that you can use to configure or manage the running instance. Instance metadata is divided into categories, for example, host name, events, and security groups. You can also use instance metadata to access user data that you specified when launching your instance.


1 Answers

The following bash script returns the Name of your current ec2 instance (the value of the "Name" tag). Modify TAG_NAME to your specific case.

TAG_NAME="Name" INSTANCE_ID="`wget -qO- http://instance-data/latest/meta-data/instance-id`" REGION="`wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`" TAG_VALUE="`aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=$TAG_NAME" --region $REGION --output=text | cut -f5`" 

To install the aws cli

sudo apt-get install python-pip -y sudo pip install awscli 

In case you use IAM instead of explicit credentials, use these IAM permissions:

{   "Version": "2012-10-17",   "Statement": [     {           "Effect": "Allow",       "Action": [ "ec2:DescribeTags"],       "Resource": ["*"]     }   ] } 
like image 173
itaifrenkel Avatar answered Oct 18 '22 21:10

itaifrenkel