Query EC2 tags from within instance

Josh Lindsey picture Josh Lindsey · Oct 7, 2010 · Viewed 98k times · Source

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?

Answer

itaifrenkel picture itaifrenkel · Jul 3, 2014

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": ["*"]
    }
  ]
}