131

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?

1
  • 1
    The solution (in 2023) is to call the magic url curl http://169.254.169.254/latest/meta-data/tags/instance. This will return a string list of tags (e.g. Environment Name ), and then you just append them to the url eg curl http://169.254.169.254/latest/meta-data/tags/instance/Environment which returns the text value of the tag.
    – Tobin
    Commented Sep 15, 2023 at 8:39

21 Answers 21

84

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": ["*"]
    }
  ]
}
4
  • I was getting "You are not authorized to perform this operation" with aws ec2 describe-tags. I needed to add this IAM to the inline policies of my IAM role. Thanks!
    – Victor D.
    Commented Jan 5, 2016 at 16:06
  • 3
    A very slight optimization COULD be to replace the | cut -f5 with --query="Tags[0].Value". Commented Jun 24, 2020 at 17:07
  • I would just like to say that this is the best answer to a question I've seen in a while. Concise, complete, task oriented. It includes unasked for but entirely reasonable additional info. I'd like to suggest that everyone everywhere write documentation in this style.
    – joar
    Commented May 6, 2021 at 15:53
  • You need AWS credentials installed. Which is not covered here.
    – EnzoR
    Commented Jun 16, 2022 at 18:05
47

Once you've got ec2-metadata and ec2-describe-tags installed (as mentioned in Ranieri's answer above), here's an example shell command to get the "name" of the current instance, assuming you have a "Name=Foo" tag on it.

Assumes EC2_PRIVATE_KEY and EC2_CERT environment variables are set.

ec2-describe-tags \
  --filter "resource-type=instance" \
  --filter "resource-id=$(ec2-metadata -i | cut -d ' ' -f2)" \
  --filter "key=Name" | cut -f5

This returns Foo.

6
  • 17
    It would have been nice if my processes could get the tags for the current instance without having to have the EC2_PRIVATE_KEY on the instance as well. :-( Commented Oct 10, 2012 at 21:33
  • 1
    @william-payne Yeah, that is really lame. Perhaps using Amazon's IAM you could at least use a user with very limited access to anything. FWIW, I don't use this approach any more and just use external scripts to setup the box.
    – overthink
    Commented Oct 15, 2012 at 21:46
  • 12
    @WilliamPayne You can set up an IAM Role with the "Amazon EC2 Read Only Access" policy and create the instance having that role. It is also possible to create a custom policy having only the "DescribeTags" privilege if you want to be more granular.
    – roverwolf
    Commented Oct 17, 2012 at 15:04
  • @WilliamPayne I liked roverwolf's suggestion. It worked great. I actually answered another question with the details if you want to see it: stackoverflow.com/questions/9950586/…
    – Tony
    Commented Aug 20, 2014 at 23:43
  • 2
    Note that ec2-describe-tags defaults to us-east-2. Please pass the --region flag to use a different region.
    – advait
    Commented May 5, 2015 at 22:28
34

You can use a combination of the AWS metadata tool (to retrieve your instance ID) and the new Tag API to retrieve the tags for the current instance.

7
  • OK, I followed that link, and it looks like it's the API documentation. Is there no tool that I can use, or do I need to read the API documentation and write my own tool? Commented Apr 8, 2012 at 19:33
  • 3
    Is the ec2-describe-tags command easily available? Supposedly it's in the ec2-api-tools package, but I got nothing but 404's when I tried to install it. Commented Apr 8, 2012 at 19:39
  • 2
    give a example, get tag role 's value: aws ec2 describe-tags --filters Name=resource-id,Values=ec2metadata --instance-id --out=json|jq '.Tags[]| select(.Key == "role")|.Value'
    – jolestar
    Commented Apr 25, 2015 at 2:14
  • 27
    This is a pointer to an answer but not an answer in-and-of itself Commented Jan 5, 2017 at 0:02
  • 3
    The ec2metadata tool is deprecated. Now you query the 'magic' URL at 169.254.169.254/latest/meta-data - hit it with cURL and it gives you magic endpoints you can use to get various bits of data. In this case curl http://169.254.169.254/latest/meta-data/instance-id gets your your instance ID Commented Jan 31, 2019 at 11:51
20

You can add this script to your cloud-init user data to download EC2 tags to a local file:

#!/bin/sh
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 's/.$//'`
aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | sed -r 's/TAGS\t(.*)\t.*\t.*\t(.*)/\1="\2"/' > /etc/ec2-tags

You need the AWS CLI tools installed on your system: you can either install them with a packages section in a cloud-config file before the script, use an AMI that already includes them, or add an apt or yum command at the beginning of the script.

In order to access EC2 tags you need a policy like this one in your instance's IAM role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1409309287000",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeTags"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

The instance's EC2 tags will available in /etc/ec2-tags in this format:

FOO="Bar"
Name="EC2 tags with cloud-init"

You can include the file as-is in a shell script using . /etc/ec2-tags, for example:

#!/bin/sh
. /etc/ec2-tags
echo $Name

The tags are downloaded during instance initialization, so they will not reflect subsequent changes.


The script and IAM policy are based on itaifrenkel's answer.

4
  • a+ prefer this method
    – Cmag
    Commented May 19, 2015 at 15:36
  • too bad this breaks for tags created by autoscaling groups: aws:autoscaling:groupName
    – Cmag
    Commented May 19, 2015 at 15:36
  • 2
    Then try this: aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | sed -r 's/TAGS\t(.*)\t.*\t.*\t(.*)/EC2_TAG_\1="\2"/' |sed -r 's/aws:autoscaling:/aws_autoscaling_/' > /etc/ec2-tags Commented Jun 23, 2015 at 23:45
  • You no longer need to chop up the availability zone; you can directly retrieve http:/169.254.169.254/latest/meta-data/placement/region
    – ThrawnCA
    Commented Feb 23 at 0:17
11

If you are not in the default availability zone the results from overthink would return empty.

ec2-describe-tags \
   --region \
     $(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone  | sed -e "s/.$//") \
   --filter \
     resource-id=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id)

If you want to add a filter to get a specific tag (elasticbeanstalk:environment-name in my case) then you can do this.

ec2-describe-tags \
   --region \
     $(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone  | sed -e "s/.$//") \
   --filter \
     resource-id=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id) \
   --filter \
     key=elasticbeanstalk:environment-name | cut -f5

And to get only the value for the tag that I filtered on, we pipe to cut and get the fifth field.

ec2-describe-tags \
  --region \
    $(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone  | sed -e "s/.$//") \
  --filter \
    resource-id=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id) \
  --filter \
    key=elasticbeanstalk:environment-name | cut -f5
1
  • great work , thank you , having a different dns instance-data is not working for me , for the last one if you need the Name tag replace elasticbeanstalk:environment-name with Name
    – detzu
    Commented Mar 18, 2019 at 22:44
9

You can alternatively use the describe-instances cli call rather than describe-tags:

This example shows how to get the value of tag 'my-tag-name' for the instance:

TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 10"`
aws ec2 describe-instances \
  --instance-id $(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id) \
  --query "Reservations[*].Instances[*].Tags[?Key=='my-tag-name'].Value" \
  --region ap-southeast-2 --output text

Change the region to suit your local circumstances, or retrieve it using one of the other answers to this question. This may be useful where your instance has the describe-instances privilege on itself, but not describe-tags in the instance profile policy

8

Starting January 2022, this should be also available directly via ec2 metadata api (if enabled).

curl http://169.254.169.254/latest/meta-data/tags/instance

https://aws.amazon.com/about-aws/whats-new/2022/01/instance-tags-amazon-ec2-instance-metadata-service/

7

I have pieced together the following that is hopefully simpler and cleaner than some of the existing answers and uses only the AWS CLI and no additional tools.

This code example shows how to get the value of tag 'myTag' for the current EC2 instance:

Using describe-tags:

export AWS_DEFAULT_REGION=us-east-1
instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
aws ec2 describe-tags \
  --filters "Name=resource-id,Values=$instance_id" 'Name=key,Values=myTag' \
  --query 'Tags[].Value' --output text

Or, alternatively, using describe-instances:

aws ec2 describe-instances --instance-id $instance_id \
  --query 'Reservations[].Instances[].Tags[?Key==`myTag`].Value' --output text
5

For Python:

from boto import utils, ec2
from os import environ

# import keys from os.env or use default (not secure)
aws_access_key_id = environ.get('AWS_ACCESS_KEY_ID', failobj='XXXXXXXXXXX')
aws_secret_access_key = environ.get('AWS_SECRET_ACCESS_KEY', failobj='XXXXXXXXXXXXXXXXXXXXX')

#load metadata , if  = {} we are on localhost
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
instance_metadata = utils.get_instance_metadata(timeout=0.5, num_retries=1)
region = instance_metadata['placement']['availability-zone'][:-1]
instance_id = instance_metadata['instance-id']

conn = ec2.connect_to_region(region, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
# get tag status for our  instance_id using filters
# http://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/ApiReference-cmd-DescribeTags.html
tags = conn.get_all_tags(filters={'resource-id': instance_id, 'key': 'status'})
if tags:
    instance_status = tags[0].value
else:
    instance_status = None
    logging.error('no status tag for '+region+' '+instance_id)
2
  • Legit. Readers note for basic local info you don't even need credentials, just the instance_metadata = utils.get_instance_metadata(timeout=0.5, num_retries=1)
    – Bartvds
    Commented May 14, 2015 at 13:15
  • Also, this plays nicely with IAM roles - if you set an instance role, boto will automatically detect the ID and key.
    – dbn
    Commented Jun 12, 2017 at 19:41
4

A variation on some of the answers above but this is how I got the value of a specific tag from the user-data script on an instance

REGION=$(curl http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')

INSTANCE_ID=$(curl -s http://instance-data/latest/meta-data/instance-id)

TAG_VALUE=$(aws ec2 describe-tags --region $REGION --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values='<TAG_NAME_HERE>'" | jq -r '.Tags[].Value')
4

It is possible to get Instance tags from within the instance via metadata.

First, allow access to tags in instance metadata as explained here

Then, run this command for IMDSv1, Refer

curl http://169.254.169.254/latest/meta-data/tags/instance/Name

or this command for IMDSv2

TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
&& curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/tags/instance
3

Jq + ec2metadata makes it a little nicer. I'm using cf and have access to the region. Otherwise you can grab it in bash.

aws ec2 describe-tags --region $REGION \
--filters "Name=resource-id,Values=`ec2metadata --instance-id`" | jq --raw-output \
'.Tags[] | select(.Key=="TAG_NAME") | .Value'

No jq.

aws ec2 describe-tags --region us-west-2 \
--filters "Name=resource-id,Values=`ec2-metadata --instance-id | cut -d " " -f 2`" \
--query 'Tags[?Key==`Name`].Value' \
--output text
1
  • This should have more upvotes in 2019 and beyond as many of the other answers no longer work. CLI version 2 perhaps? In any case this worked for me out of the box but you do need to have the describe-tags permission granted to the instance's IAM role. Oh and get the right region with ec2-metadata -z | sed 's/.$//' as per other answers.
    – biomiker
    Commented May 28, 2021 at 15:59
2

Using the AWS 'user data' and 'meta data' APIs its possible to write a script which wraps puppet to start a puppet run with a custom cert name.

First start an aws instance with custom user data: 'role:webserver'

#!/bin/bash

# Find the name from the user data passed in on instance creation
USER=$(curl -s "http://169.254.169.254/latest/user-data")
IFS=':' read -ra UDATA <<< "$USER"

# Find the instance ID from the meta data api
ID=$(curl -s "http://169.254.169.254/latest/meta-data/instance-id")
CERTNAME=${UDATA[1]}.$ID.aws

echo "Running Puppet for certname: " $CERTNAME
puppet agent -t --certname=$CERTNAME 

This calls puppet with a certname like 'webserver.i-hfg453.aws' you can then create a node manifest called 'webserver' and puppets 'fuzzy node matching' will mean it is used to provision all webservers.

This example assumes you build on a base image with puppet installed etc.

Benefits:

1) You don't have to pass round your credentials

2) You can be as granular as you like with the role configs.

2

The solution (in 2023) is to call the magic url curl http://169.254.169.254/latest/meta-data/tags/instance. They need to be enabled in the Advanced Settings during Instance creation.

enter image description here

This will return a string list of tags (e.g. Environment\nName ), and then you just append them to the url eg curl http://169.254.169.254/latest/meta-data/tags/instance/Environment which returns the text value of the tag.

1

Download and run a standalone executable to do that.

Sometimes one cannot install awscli that depends on python. docker might be out of the picture too.

Here is my implementation in golang: https://github.com/hmalphettes/go-ec2-describe-tags

1

The Metadata tool seems to no longer be available, but that was an unnecessary dependency anyway.

Follow the AWS documentation to have the instance's profile grant it the "ec2:DescribeTags" action in a policy, restricting the target resources as much as you wish. (If you need a profile for another reason then you'll need to merge policies into a new profile-linked role).

Then:

aws --region $(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone  | sed -e 's/.$//') ec2 describe-tags --filters Name=resource-type,Values=instance Name=resource-id,Values=$(curl http://169.254.169.254/latest/meta-data/instance-id) Name=key,Values=Name |
perl -nwe 'print "$1\n" if /"Value": "([^"]+)/;'
1

Well there are lots of good answers here but none quite worked for me exactly out of the box, I think the CLI has been updated since some of them and I do like using the CLI. The following single command works out of the box for me in 2021 (as long as the instance's IAM role is allowed to describe-tags).

aws ec2 describe-tags \
--region "$(ec2-metadata -z | cut -d' ' -f2 | sed 's/.$//')" \
--filters "Name=resource-id,Values=$(ec2-metadata --instance-id | cut -d " " -f 2)" \
--query 'Tags[?Key==`Name`].Value' \
--output text
1

AWS has recently announced support for instance tags in Instance Metadata Service: https://aws.amazon.com/about-aws/whats-new/2022/01/instance-tags-amazon-ec2-instance-metadata-service/

If you have have the tag metadata option enabled for an instance, you can simply do

$ TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 900"`
$ curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/tags/instance
1
  • A nice updated answer :) Worth mention that metadata option for tags is Disabled by default
    – Enin Kaduk
    Commented Feb 15, 2023 at 8:20
0

Install AWS CLI:

curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"
sudo apt-get install unzip
unzip awscli-bundle.zip
sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws

Get the tags for the current instance:

aws ec2 describe-tags --filters "Name=resource-id,Values=`ec2metadata --instance-id`"

Outputs:

{
    "Tags": [
        {
            "ResourceType": "instance", 
            "ResourceId": "i-6a7e559d", 
            "Value": "Webserver", 
            "Key": "Name"
        }
    ]
}

Use a bit of perl to extract the tags:

aws ec2 describe-tags --filters \
"Name=resource-id,Values=`ec2metadata --instance-id`" | \
perl -ne 'print "$1\n" if /\"Value\": \"(.*?)\"/'

Returns:

Webserver
3
  • ec2metadata isn't in aws-cli, but it can be replaced with curl --silent http://169.254.169.254/latest/meta-data/instance-id. also, jq can parse the json easier, or a different output format is even easier. Commented Aug 4, 2015 at 21:35
  • This works, however I need to add following: sudo apt-get -y install python and export AWS_DEFAULT_REGION=us-west-1
    – Eugene
    Commented Aug 26, 2019 at 0:53
  • This will not work... 1. ec2metadata is incorrect command. 2. ec2-metadata --instance-id will return instance-id: i-07f59f3564618f148 Commented Jul 25, 2020 at 17:17
0

For those crazy enough to use Fish shell on EC2, here's a handy snippet for your /home/ec2-user/.config/fish/config.fish. The hostdata command now will list all your tags as well as the public IP and hostname.

set -x INSTANCE_ID (wget -qO- http://instance-data/latest/meta-data/instance-id)
set -x REGION (wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')

function hostdata
    aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | sed -r 's/TAGS\t(.*)\t.*\t.*\t(.*)/\1="\2"/'
    ec2-metadata | grep public-hostname
    ec2-metadata | grep public-ipv4
end
0

To add the above answers if you have awsPowerShell tools installed you can get instance-id with

Get-EC2InstanceMetadata -Category  InstanceId

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.