HOME  → POSTS  → 2014

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")
}

Notes

  • 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.

References

is an engineering manager with over 20 years of experience across software development, site reliability engineering, and security. He is the creator of SimplePie and AWS SDK for PHP, patented multifactor-authentication-as-a-service at WePay, defined much of the CI/CD and SRE disciplines at McGraw-Hill Education, and came up with the idea of “serverless, event-driven, responsive functions in the cloud” while at Amazon Web Services in 2010. Ryan's aptly-named blog, , is where he writes about ideas longer than . Ambivert. Curious. Not a coffee drinker.