Monday, March 23, 2015

Use a Config File for Easy SSH Connections.

Problem ?

When working with Amazon EC2 instances its pretty annoying to connect to the instances using SSH. All the time we have to give the path to the pem file, the username of the EC2 instances, the public DNS for the instance. This is pretty much annoying.

$ ssh -i Key.pem ubuntu@ec2-11-11-11-11.xx-xxxx-xx.compute.amazonaws.com

But there is an easier way that you can store all those variables in a config file an use it to connect the instances from any folder.

Solution

Go to the root directory using "CD".

$ cd

Go the to ".ssh" folder. This folder might already be there.

$ cd .ssh/

Create a file named "config" using an editor. I'll be using VIM.

$ vim config

The config file should contain all our variables for the EC2 instances or where ever you are connecting to. Lets say we have the following EC2 instances.

ID Username Public DNS PEM File Path
instance1 ubuntu ec2-11-11-11-11.xx-xxxx-xx.compute.amazonaws.com ~/.ssh/pems/Key.pem
instance2 ubuntu ec2-22-22-22-22.xx-xxxx-xx.compute.amazonaws.com ~/.ssh/pems/Key.pem
instance3 ubuntu ec2-33-33-33-33.xx-xxxx-xx.compute.amazonaws.com ~/.ssh/pems/Key.pem

In the above table, the ID is a unique value for each instance. You can use any value for the ID. Username is the login username for the instance. Public DNS is the host name for the instance. The PEM File Path is the file path for the identity file.

Using those data we can create the config file content as follows.

Host instance1
    User ubuntu
    Hostname ec2-11-11-11-11.xx-xxxx-xx.compute.amazonaws.com
    IdentityFile ~/.ssh/pems/Key.pem

Host instance2
    User ubuntu
    Hostname ec2-22-22-22-22.xx-xxxx-xx.compute.amazonaws.com
    IdentityFile ~/.ssh/pems/Key.pem

Host instance3
    User ubuntu
    Hostname ec2-33-33-33-33.xx-xxxx-xx.compute.amazonaws.com
    IdentityFile ~/.ssh/pems/Key.pem

After saving the "config" file, you can connect to any of those instances from any folder. If you want to connect to "instance2", it will be as follows.

$ ssh instance2

Happy SSH-ing!

No comments:

Post a Comment