Skip to content

cannot get ec2 name from within ec2

0

I thought this task would be super simple but nothing is working. I want to get the name of the ec2 from within the ec2. I keep running across commands like INSTANCE_ID=$(curl -s http://169.254.169.254)

when I run it, nothing is returned. I have tried a million different things, but this command comes up in almost every article I read, but does nothing.

How can I get the name of my ec2 instance from within it?

asked 4 days ago18 views
2 Answers
1

The command you're using is incomplete - you need to specify the full metadata path. To get instance metadata from within an EC2 instance, you need to access the Instance Metadata Service (IMDS) using the complete URI.

Here's how to get your instance ID (which is different from the instance name):

For IMDSv2 (recommended):

TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
INSTANCE_ID=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id)

For IMDSv1:

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

However, the "Name" tag of an EC2 instance is not directly available through instance metadata by default. The Name is actually a tag, and tags need to be explicitly enabled in the instance metadata. If instance tags are enabled, you can retrieve the Name tag like this:

For IMDSv2:

TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
NAME=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/tags/instance/Name)

If you're still getting no response, check that:

  1. You don't have firewall rules blocking access to the metadata service (169.254.169.254)
  2. You're including the full path (/latest/meta-data/ followed by the specific metadata item you want)
  3. Instance tags are enabled in your instance metadata options if you're trying to access the Name tag
    Sources
    Troubleshoot IAM and Amazon EC2 - AWS Identity and Access Management
    Use the Instance Metadata Service to access instance metadata - Amazon Elastic Compute Cloud
    Access instance metadata for an EC2 instance - Amazon Elastic Compute Cloud
answered 4 days ago
EXPERT
reviewed 4 days ago
0

In case, you want to get the name tags, you can try,

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" http://169.254.169.254/latest/meta-data/tags/instance

on linux.

Refer: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/work-with-tags-in-IMDS.html

EXPERT
answered 4 days ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.