How to get an instance ID on AWS EC2 instance

How to get an instance ID on AWS EC2 instance
Photo by Sai Kiran Anagani / Unsplash

Hey everyone!

Hope you are safe and doing great!

When we try to automate some of our projects within AWS EC2 instances, getting instances ID via a terminal/script might be pretty helpful.

In this short guide, we will see how we can accomplish this.

1. Via cat command

cat /sys/devices/virtual/dmi/id/board_asset_tag

2. Via aws ec2 describe-instances command

ip=$(hostname -I | awk {'print $1'})
aws ec2 describe-instances --filters Name=private-ip-address,Values=$ip | grep InstanceId | awk {'print $2'} | tr -d \",

3. Official AWS way

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/instance-id

4. Variables adapted way

TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
AWS_REGION=`/usr/bin/curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/placement/region`
EC2_INSTANCE_ID=`/usr/bin/curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/instance-id`

You are awesome!

That is it. Hope this short guide helped you and saved your time for the best.

Thank you for reading and see you soon.

Read more