11

I can get the internal hostname of an instance with the hostname command. How do I get the external host name from within the instance?

Specifically I'm on EY and using the ey ssh command, I want to know what the host name is so I can pass this to scp.

6 Answers 6

13

From within the instance, you can hit the Instance Metadata Service:

curl http://169.254.169.254/latest/meta-data/public-hostname

or

curl http://instance-data.ec2.internal/latest/meta-data/public-hostname

A wide variety of data is available via this interface.

5
  • curl: (6) Could not resolve host: instance-data.ec2.internal Jun 28, 2023 at 18:37
  • @PeterKionga-Kamau And did you try the IP-based approach?
    – ceejayoz
    Jun 30, 2023 at 17:58
  • No, IPs change and can't be relied upon indefinitely. Ended up using a combination of ec2metadata and nslookup Jul 1, 2023 at 21:46
  • 1
    @PeterKionga-Kamau 169.254.169.254 isn't likely to change on the AWS end.
    – ceejayoz
    Jul 1, 2023 at 23:34
  • It doesn't matter how unlikely it is, if it is possible and it is avoidable then it is an unnecessary failure point. Jul 2, 2023 at 20:37
7

/opt/aws/bin/ec2-metadata -p will print the public hostname of that instance.

1
  • -bash: /opt/aws/bin/ec2-metadata: No such file or directory - Instead use ec2metadata --public-hostname as described by @calvin-huang below Jun 28, 2023 at 18:37
4

It is very simple by ec2 instance metadata query tool.

run command:

./ec2-metadata --public-ipv4

or:

./ec2-metadata --public-hostname

for more information, just pass --help to ec2-metadata

1
  • -bash: ./ec2-metadata: No such file or directory instead use ec2metadata --public-hostname as described by @calvin-huang below Jun 28, 2023 at 18:38
2

Currently, on EC2 instances you can use:

$ ec2metadata --public-hostname
1

I don't know what system you use but I assume a Linux. You can either connect directly to your IP address or try a reverse lookup of this ip with for example

host -a <ip_address>

You can find out your IP address if you use the command ifconfig that will print out all information on the network interfaces.

1
  • If the host name is unknown, it is highly likely that the IP address is also unknown (at least, by whatever script is trying to find it). Jun 28, 2023 at 18:39
0
public_hostname=$(timeout 2 ec2metadata --public-hostname 2> /dev/null)
if [ -z "$public_hostname" ]; then # fallback to nslookup + hostname
    public_hostname=$(nslookup "$(hostname -I | awk '{print $1}')" | awk '/name/{print $NF}' | sed 's/\.$//')
fi

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .