How to get the instance Name from the instance in AWS?

58,805

Solution 1

First, you need to get the instance-id.

AWS_INSTANCE_ID=`curl -s http://169.254.169.254/latest/meta-data/instance-id`

Than you can get the ec2 instance name using below command.

EC2_NAME=$(aws ec2 describe-tags --region $REGION --filters "Name=resource-id,Values=$AWS_INSTANCE_ID" "Name=key,Values=Name" --output text | cut -f5)

Please ensure that you have AWS Cli Installed.

I hope this helps. Thanks!

Solution 2

First and foremost, the Amazon EC2 Instance Metadata Service also provides quite some other Names besides the instance-id, if these might be what you are looking for - see Instance Metadata Categories:

  • hostname - The private hostname of the instance. In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).
  • local-hostname - The private DNS hostname of the instance. In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).
  • public-hostname - The instance's public DNS. If the instance is in a VPC, this category is only returned if the enableDnsHostnames attribute is set to true.

If you are looking for the Name as exposed in the AWS Management Console though, you would indeed need to resort to using one of the Tools for Amazon Web Services to retrieve it - that Name is in fact just a regular tag with the key Name (see Tagging Your Amazon EC2 Resources), which happens to be used across most AWS services for the obvious purpose.

Here's how to get it with the AWS Command Line Interface for example (skipping region and credentials):

aws ec2 describe-tags \
--filters Name=resource-id,Values=i-abcd1234 Name=key,Values=Name \
--query Tags[].Value --output text
Share:
58,805
numb3rs1x
Author by

numb3rs1x

Updated on August 06, 2021

Comments

  • numb3rs1x
    numb3rs1x almost 3 years

    I'm trying to set up a means to register an instance in route53 automatically when the instance is created, using salt and this article.

    The article uses ec2-metadata to get the instance-id and and the hostname. I'm wondering if there is a way, using bash within the instance, to get the instance Name instead. ec2-metadata only seems to show the instance-id. Thanks in advance.