I have name of the a ec2 instance and want to do ssh to it. How can I figure out the 'Public DNS' of the ec2 instance using the ec2 instance name.
I want to do it using bash.
I have name of the a ec2 instance and want to do ssh to it. How can I figure out the 'Public DNS' of the ec2 instance using the ec2 instance name.
I want to do it using bash.
aws ec2 describe-instances --instance-ids i-12abc34 --query 'Reservations[].Instances[].PublicDnsName'
Where i-12abc34 is your instance id
You can query the instance metadata service.
Using curl:
curl -s http://169.254.169.254/latest/meta-data/public-hostname
Using wget:
wget -qO - http://169.254.169.254/latest/meta-data/public-hostname
If brave, actual bash:
exec 3<> /dev/tcp/169.254.169.254/80
echo -e "GET /latest/meta-data/public-hostname HTTP/1.0\r\n\r\n" >&3
cat <&3
(The last one leaves the connection open for me, so the cat
gets stuck. The headers are also present in the output)
(This is from the instance itself and need access to the instnace - it is not the instance name-related version. There are enough of those answers here)
Using the EC2 API tools:
# Region is only needed if not in us-east-1
$ ec2-describe-instances --region <region> <instance id>
Using the unified AWS CLI tool:
$ aws --region <region> ec2 describe-instances --instance-ids <instance id≥
I prefer the unified tool as it offers comprehensive and consistent data.
If you install the cloud-utils tool as described in this answer it's much more straight forward.
https://stackoverflow.com/a/10600619/28672
ec2-metadata --public-ipv4
> public-ipv4: 54.200.4.52
It depends on what you mean by "figure out". If you mean figuring out yourself, you cannot. The public DNS name has nothing to do with the ec2 instance name. The public DNS name is composed of public IP address, region/availability zone, type of service, aws domain name, etc. For example, ec2-xx-xxx-x-xx.us-west-2.compute.amazonaws.com. Because the public IP address is changed every time you stop and start your instance, unless you use an elastic IP address, your public DNS name will be changed.
If you mean figure out by using AWS API or CLI tool, you can. Using EC2 CLI, you should use command ec2-describe-instances instance_id. Again, the instance has to be running and the public DNS does change after stop/start.