BenCr
BenCr

Reputation: 6052

Is it possible to get an EC2 instances tags using the metadata api?

Also if it's not possible to get the tags using the metadata api do you get charged for calling the EC2 web service from an EC2 instance? i.e. would it be better to just encode the tags in the user data which is available internally for free.

Upvotes: 1

Views: 3052

Answers (2)

Junaid
Junaid

Reputation: 3945

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 the tag metadata option enabled for an instance, you can simply run:

$ 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
Tag1-Key
Tag2-Key

$ curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/tags/instance/Tag1_Key
Tag1_Value

Upvotes: 1

Peter Stephens
Peter Stephens

Reputation: 1080

The instance metadata does not contain tag information. See http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/instancedata-data-categories.html for the list of metadata categories.

The metadata does include the instance id which can be used along with the EC2 API to retrieve the tags.

There should be no concern about price for calling the EC2 APIs. You are not charged by the API call for EC2.

Upvotes: 4

Related Questions