DEV Community

Cover image for Automatically Update Security Group When SSHing into Your Server
C.J. Windisch
C.J. Windisch

Posted on

Automatically Update Security Group When SSHing into Your Server

Often times I’m working from a coffee shop, a friend or family members house, an airport, or somewhere else random. Then I try to ssh into my server to do something and it hangs.

Troubleshooting EC2 SSH Connection Issues

SSH is not particularly helpful in informing you what's happening when you're trying to fix EC2 SSH problems. Eventually I realize there's an EC2 SSH connection timeout because I have to add my IP to the security group before I can ssh.

I made a useful bash script and shortcut to check if ssh is available and if not use the aws cli to add my current ip to the security group then try again.

I know, probably not great adding a public network IP to the security group, but when you gotta get work done you gotta get work done.

Here’s the code:


function ssh_into_ec2() {
  HOST="ec2-11-111-11-111.us-east-2.compute.amazonaws.com" # Change to your region and ec2 public url
  USER=ec2-user SSH_STRING="ec2-user@$HOST" # Change if you use a different username
  HOST_URL="https://$HOST"
  SSH_KEY=your-key-file.pem # point to your keyfile
  echo "Checking if ssh to $HOST is reachable"
  if timeout 2 nc -z $HOST 22; then
    echo "Reachable. SSHing into $HOST"
    ssh -v -i $SSH_KEY "$USER@$HOST"
  else
    echo "ssh to $HOST not reachable, adding current IP to security group"
    SECURITY_GROUP="your-security-group" # Change to the name of your EC2 server's security group
    PUBLIC_IP=$(curl ifconfig.me)
    aws ec2 authorize-security-group-ingress \
      --group-name $SECURITY_GROUP \
      --protocol tcp \
      --port 22 \
      --cidr $PUBLIC_IP/32
    ssh -v -i $SSH_KEY "$USER@$HOST"
  fi
}
Enter fullscreen mode Exit fullscreen mode

Resources that helped make the code:

How to find if a server is reachable over ssh
How to check if nc succeeded in a bash script
How to check the exit status using an if statement
Finding my IP from the command line

Top comments (0)