- Newest
- Most votes
- Most comments
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:
- You don't have firewall rules blocking access to the metadata service (169.254.169.254)
- You're including the full path (
/latest/meta-data/followed by the specific metadata item you want) - 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
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
