Easily SSH into Amazon EC2 instances using the Name tag

Projects and Code268 words2 minutes to read

It’s been a while since I’ve written about code, so I thought I’d post this little AWS-related tip for OS X and Linux users.

If you have the Unified AWS CLI Tools configured, you can add these functions to your Bash profile (typically either ~/.bash_profile or ~/.profile) to enable you to SSH into an instance by “Name” tag, or simply lookup the IP address or DNS hostname.

hostname_from_instance <instance-name>

ip_from_instance <instance-name>

ssh-aws <instance-name>

Bash code

function hostname_from_instance() {
    echo $(aws ec2 describe-instances --filters "{\"Name\":\"tag:Name\", \"Values\":[\"$1\"]}" --query='Reservations[0].Instances[0].PublicDnsName' | tr -d '"')

function ip_from_instance() {
    echo $(aws ec2 describe-instances --filters "{\"Name\":\"tag:Name\", \"Values\":[\"$1\"]}" --query='Reservations[0].Instances[0].PublicIpAddress' | tr -d '"')

function ssh-aws() {
    ssh -i ~/.ssh/your-keypair.pem ec2-user@$(ip_from_instance "$1")


  • This assumes that every instance you have has a unique “Name” tag, and will return the IP address or public DNS hostname of that instance (for use with SSH access). If multiple instances share the same “Name” tag, it will simply use the first “Name” match.

  • If you’re running instances inside a (private) VPC, you should expect to lookup the public Elastic IP address for the instance.

  • If you’re running instances inside a (public, classic) EC2, you should expect to lookup the public DNS hostname (unless you’ve configured an Elastic IP — in which case, go nuts).

  • In the case where you’re running instances in the private subnet of a VPC, and SSH access to those instances is only possible from a bastion host in the public subnet, this is not the solution for you.

Feel free to tweak/adjust as necessary.


Ryan Parman

Ryan Parman is an experienced software engineer, open source evangelist, and passionate user advocate currently living in Seattle. He is the creator of and , and worked on DevOps and Security at . He is now bringing learning into the digital age as an Engineering Lead and Site Reliability Engineer at . Ryan's aptly-named blog, , is where he writes about ideas longer than .