DEV Community

Cover image for A good way to set up SSH keys for Git on Macbooks
scottshipp
scottshipp

Posted on

A good way to set up SSH keys for Git on Macbooks

Motivation for this article

At least once or twice a year, I either set up new SSH keys for access to a new Git repository or else I set up the same keys on a new Macbook. Every time, I feel like I learn something new and this last time, I finally felt like I got it right. These are the notes.

Creating an SSH keypair

Creating a keypair is the easy part. Generally, you can follow exactly whatever help documentation is provided by your particular Git platform, whether that's GitHub, Gitlab, or Bitbucket.

The Password Problem

Once you create the keypair, and store it into the platform, the first problem occurs, which is that you always have to enter your password to unlock the key.

For a long time, I would add the following to my .bashrc or .zshrc, simply because other developers told me to do this.

Don't do this.

# BAD IDEA: adding the following to the .zshrc file
eval $(ssh-agent)
ssh-add
Enter fullscreen mode Exit fullscreen mode

The main reason not to do that is that although this lets you avoid entering your SSH key password every time you try to use the git cli, it still requires you to enter your password every time you open a new terminal.

The solution

At some point, I read Danila Vershinin's excellent article Proper use of SSH client in Mac OS X. It blew my mind 🤯 because I didn't realize that Mac OS has a built-in integration between the Keychain and OpenSSH.

You can use this integration with a one-time configuration ("set it and forget it").

First, add the following to $HOME/.ssh/config:

UseKeychain    yes
AddKeysToAgent yes
Enter fullscreen mode Exit fullscreen mode

Next, add each key with the -K argument, which is Mac-specific and will save the key password into the Keychain.

$ ssh-add -K ~/.ssh/<<YOUR_KEY_FILE>>
Enter fullscreen mode Exit fullscreen mode

That's all there is to it.

Conclusion

This is a good way to set up SSH keys for Git on Macbooks. There's also a way to configure for multiple keys and multiple Git platforms which you can check out here.

If you have anything to add, I'd be glad to hear it in the comments below. 👍

Discussion (0)