SSH: defining aliases to use different keys for the same host

· adduc's blog


Context #

I have multiple Github accounts (work, personal, other projects), but Github requires each Github account to use a unique SSH key. I would like to define unique host aliases for each Github account to allow me to push to repositories using the correct key.

Solution #

Use separate aliases for each Github account, and use the IdentityFile configuration and IdentitiesOnly to force SSH to use the correct key for each alias.

Host github-user1
  Hostname github.com
  IdentityFile ~/.ssh/keys.d/GithubUser1
  IdentitiesOnly yes

Host github-user2
  Hostname github.com
  IdentityFile ~/.ssh/keys.d/GithubUser2
  IdentitiesOnly yes

We can test this out using ssh:

1ssh git@github-user1
2# Hi github-user1! You've successfully authenticated, but GitHub does not provide shell access.
3
4ssh git@github-user2
5# Hi github-user2! You've successfully authenticated, but GitHub does not provide shell access.

If the second command shows that you've authenticated as github-user1, you may be reusing SSH connections. See the section below a method to fix this.

Gotcha: Reusing SSH connections #

It's common to configure SSH to reuse connections to the same host. This is typically done using the following configuration:

Host *
  ControlPath ~/.ssh/socket-%r@%h:%p
  ControlMaster auto
  ControlPersist yes

This configuration tells SSH to create a socket for each host, and to reuse that socket for future connections to the same host. This is useful for eliminating the overhead of creating a new SSH connection for each shell session, but SSH reuses the same keyfile for each connection to the socket.

Since we want to use different keys when accessing github.com, we need to use a slightly different configuration to create a unique socket for each aliases:

Host *
    ControlPath ~/.ssh/socket-%r@%k:%p
    ControlMaster auto
    ControlPersist yes

%h is replaced with the hostname, and %k is replaced with the host alias. Using %k allows us to create a unique socket for each host alias, which would allow us to use different keys for connecting to the same host, and for the connections to remain open for future connections.