SSH key setup for ssh and git
For me, ssh gets used daily, from logging to remove servers and virtual machines to pushing and pulling code with [[git]]. To make this process a bit better you can set up ssh key pairs. This provides better security and for your main production servers and passwordless auth for your git servers and any other lower priority server.
My main workflow is to have two ssh key pairs. One with a passphrase and one without. Then I use the one with the passphrase for high security mainly just production servers. And the one without for git and automation pipelines with Jenkins CI.
Now let's get into how I set all this up.
Generating your key pairs
For generating my keys I use
ssh-keygen and create the keys with the following commands.
ssh-keygen -t rsa -C "key-name" -b 4096
ssh-keygen -t rsa -C "key-name-no-passphrase" -b 4096
The first one I put in a passphrase and use as my main key. The second I leave the passphrase blank and change the file name to
~/.ssh/id_rsa_no_paraphrase. I will explain how the two keys get configured below.
Adding the keys
Now that we have some keys we can get them on to our servers. For the production keys with the passphrases, you may need your system admin, however, git you can do yourself by going to your profile in git add configuring your account. I use gitlab and you can view there website for more information on using ssh with gitlab. If you use another git server you can refer to there docs on how to add your keys.
Because we have set up two keys. Shh will use the
id_rsa by default. So to use the key without a passphrase you need to configure ssh with a
~/.ssh/config file. The config below will tell ssh that for gitlab.com to use the no passphrase key.
The ssh config file is a really powerful tool if you're using a lot of remote machines. You can configure any parameter of the ssh command like
User. This allows you to set up ssh alias host and just run
ssh remove.server for complex ssh tunnelling commands. You can read more on the ssh config by running
The final piece of the puzzle is
ssh-agent. This allows us to securely store our passphrase so we don't have to keep putting it in. This is super handy for build scripts where you are running multiple commands on a server via ssh. Before you start your script add your key to the agent
ssh-add ~/.ssh/id_rsa this will ask you to put in your passphrase. Once you do you can use that ssh key like it has no passphrase. Once you are done running your scripts you can run
ssh-add -d ~/.ssh/id_rsd to remove that identity from the agent, or you can run
ssh-add -D to remove all identities from the agent. Then you are back to putting in your passphrase.