# How to connect to the same host with different SSH keys

> A quick note on using the SSH config file to give each host a short name and its own key, such as separate personal and work GitHub accounts.

- Date: 2022-08-16
- Tags: git, tutorial, devjournal
- Also on dev.to: [https://dev.to/jimzandueta/setup-your-ssh-configuration-file-1m9e](https://dev.to/jimzandueta/setup-your-ssh-configuration-file-1m9e)

I keep a personal and a work GitHub account on the same laptop, and this SSH config is how they stay apart. It builds on my note on [generating an SSH key pair](https://dev.to/jimzandueta/generate-an-ssh-key-pair-2fcc).

## Set up your SSH configuration file

To connect to a remote server over SSH, you would normally type the user name, host name and port every time:

```sh
$ ssh tony@avengers.com -p 4321
```

Add these lines to your `~/.ssh/config`, and `ssh avengers` does the same thing:

```sh
Host avengers
    HostName avengers.com
    User tony
    Port 4321
```

You can also choose which key to use for each server with `IdentityFile`:

```sh
Host avengers
    HostName avengers.com
    User tony
    Port 4321
    IdentityFile ~/.ssh/id_rsa_avengers
    
Host marvel
    HostName marvel.com
    User tony
    Port 8080
    IdentityFile ~/.ssh/id_rsa_marvel
```
`IdentityFile` is most useful when you connect to the same host with different keys. A common case is having two GitHub accounts, one personal and one for work:

```sh
Host github_personal
    HostName github.com
    IdentityFile ~/.ssh/github_personal
    
Host github_work
    HostName github.com
    IdentityFile ~/.ssh/github_work
    
# Default key for every other host
Host *
    IdentityFile ~/.ssh/id_rsa
```

Using the configuration file above, you can clone repositories from your personal GitHub account with:
```sh
$ git clone git@github_personal:tonystark/ultron.git
```

Notice that instead of `@github.com`, the host is `@github_personal`, the name defined in the configuration file.

## Updating the configuration file
- Open your favorite terminal
- Create or open the SSH configuration file
```sh
$ nano ~/.ssh/config
```

### Resources
- [SSH config file syntax](https://www.ssh.com/academy/ssh/config)
