Skip to content

Instantly share code, notes, and snippets.

@beaucronin
Last active October 26, 2016 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beaucronin/8c7fdb7850ace00f7eb540cb134f5ae2 to your computer and use it in GitHub Desktop.
Save beaucronin/8c7fdb7850ace00f7eb540cb134f5ae2 to your computer and use it in GitHub Desktop.
SSH into an EC2 instance by tag

Usage:

$ ec2-login-amazon <tag>
  • Aside from the AWS CLI tools, you'll need jq: https://stedolan.github.io/jq/
  • If multiple instances have the tag you specify, the first one will be chosen
  • There are separate commands for Amazon Linux and Ubuntu because, aside from looking at the AMI ID, there's no way to know which user name to use
#!/bin/bash
if [[ -z $SSH_DIR ]]
then
SSH_DIR="~/.ssh"
fi
PEM_SUFFIX=".pem"
result=(`aws ec2 describe-instances | \
jq -r ".Reservations[] | \
.Instances[0] | \
{ dns:.PublicDnsName, key:.KeyName, match:(.Tags[].Value // [] | select(. == \"$1\") | length > 0), state:.State.Name } | \
select(.state | contains(\"running\")) | \
.dns, .key"`)
host=${result[0]}
key=${result[1]}
ssh -i $SSH_DIR/$key$PEM_SUFFIX ec2-user@$host
#!/bin/bash
if [[ -z $SSH_DIR ]]
then
SSH_DIR="~/.ssh"
fi
PEM_SUFFIX=".pem"
result=(`aws ec2 describe-instances | \
jq -r ".Reservations[] | \
.Instances[0] | \
{ dns:.PublicDnsName, key:.KeyName, match:(.Tags[].Value // [] | select(. == \"$1\") | length > 0), state:.State.Name } | \
select(.state | contains(\"running\")) | \
.dns, .key"`)
host=${result[0]}
key=${result[1]}
ssh -i $SSH_DIR/$key$PEM_SUFFIX ubuntu@$host
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment