Saturday, May 23, 2020

Using ssh config

If you have ever used ssh before, you know it is pretty straightforward to connect to other servers and virtual machines,  ssh ip_or_hostname. You may even type it without even thinking about it. As your infrastructure grows and maybe some moves to the cloud  you may begin to need to also add a username and/or a different Identity file or private key.

 ssh -i /path/to/identity/file username@ip_or_hostname

Still pretty straightforward, it is a bit more to type out which can be annoying and slow you down when you are in a hurry.  We could simplify this a bit by adding an Alias for this command. Then we would just type our Alias and let the system handle the rest. Then all we need to remember is our Alias that we created.

What happens when the number of virtual machines you are supporting increases dramatically. What if many of those servers are for production and lower environments hosted by multiple clients. Add to that multiple git repositories for those clients as well. You can very quickly end up with quite the number of Identity files and keys to manage. If we are creating Alias commands for each of those virtual machines you will have to come up with a snappy way to remember all those Alias commands.


An alternative would be to take a few moments and add the entries to a ssh config file on the machine we are connecting from. By default OpenSSH doesn't create a config file iin your profile or home directory, but we can manually add it there.

Using your favorite text editor, create a file called 'config' in your .ssh directory. By default OpenSSH will automatically look for this file

vi ~/.ssh/config

Now we are ready to add our entries using the following format for each entry:

# This is a comment line
Host clientADev
HostName devserver.example.com 
User myUserID 
IdentityFile ~/.ssh/clientA-dev.pem
Save the file, and now we can ssh using the following command:

ssh clientADev

OpenSSH will find that host in our config file and use the HostName, User, and IdentityFile we specified to make the connection.

But what if we have a dev environment with more than 1 server and we use the same credentials for all of them. We can specify multiple entries by hostname or ip in the Host line to account for this.


# This is a comment line
Host 123.345.789 789.475.123  67.234.123
User myUserID 
IdentityFile ~/.ssh/clientA-dev.pem

Now when we ssh to any of the hosts listed OpenSSH will automatically use the proper credentials, and we no longer need to type long commands or remember which creds go to which server(s).

There are many other options we can add to the config file to better control and configure our ssh client. For more on that you may want to review the man pages on this topic.

No comments:

Post a Comment