ASCII Thoughts

SSH Config & Aliases

SSH is a wonderful tool. It has many advanced features which can make your life easier as a developer, but they are not always well known or understood. So today, let's introduce one of these: aliases.

When you are working on a project, you often have to switch between different servers: a local server, a test/staging server and a production server. So you find yourself typing this all day:

ssh user@virtual-machine
ssh [email protected]
ssh [email protected]

Some people find a workaround with shell aliases:

alias test="ssh [email protected]"

That works alright in most cases, but what happens for example when you have to use scp or a rsync: you have to type the full command again...

# SSH to production server, quick and easy
prod

# Copy a file from test server. #FAIL
scp [email protected]:/path .

The solution

Thankfully, SSH offers aliases too. They are defined in ~/.ssh/config:

Host foo
  User user
  Hostname example.com

With that configuration in place, you can now do all of the following:

# ssh [email protected]
ssh foo

# scp [email protected]:/some/path /bar
scp foo:/some/path /bar

# rsync [email protected]:/some/path /bar
rsync foo:/some/path /bar

All servers in a project

I follow a convention for all my servers and use suffixes to identify which server I'm connecting too. So let's say I want quick access to all the environments of my project example. Here is what my config would look like:

Host example.dev
  User deploy
  Hostname virtual-machine

Host example.test
  User deploy
  Hostname test.example.com

Host example.prod
  User deploy
  Hostname www.example.com

This way, I can quickly go to any of those servers, and I don't have to remember their exact name, IP address, login, etc.:

ssh example.dev    # local vm
ssh example.test   # testing server
ssh example.prod   # production server

Of course, the following now works too:

rsync -avz example.test:/var/www path

Other options

You don't have to limit yourself to User and Hostname, you can use the full range of SSH options. Here is a more advanced configuration:

Host example
  Port 678
  User special
  Hostname 88.88.88.88
  LocalForward 8000 127.0.0.1:80
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/id_example_dsa
  Compression yes

You can find more information about the options available and the general format of the file in the man:

man ssh_config

Conclusion

SSH aliases can dramatically ease your life. Use them!

Until next time, Cheers!