It's minimal, but I'm posting things.
It is useful to manage different identities depending on your Git repository, especially when working with both personal and professional repositories on the same machine.
You can achieve this by setting SSH host entries explicitly.
The fix for identity confusion is defining explicit aliases in ~/.ssh/config.
Instead of connecting to the default host, create a custom Host entry.
Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_work
IdentitiesOnly yes
Don't forget to include IdentitiesOnly yes.
It forces SSH to use only the specified key, which prevents the agent from offering other identities to the server.
insteadOfAliases are useful, but typing git clone git@github.com-work:repo every time would make it pointless.
Git’s insteadOf feature solves this by rewriting URLs.
git config --global url."git@github.com-work:".insteadOf "git@github.com:"
With this configuration, you clone using the standard URL and the routing happens automatically.
I use Ansible to ensure these configurations are consistent across every workstation.
But you certainly can automate this in any other manner.
- name: SSH - Define work identity
blockinfile:
path: "~/.ssh/config"
block: |
Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_work
IdentitiesOnly yes
marker: "# {mark} ANSIBLE MANAGED BLOCK: WORK IDENTITY"
- name: Git - Configure URL rewriting for work
git_config:
name: url."git@github.com-work:".insteadOf
value: "git@github.com:"
scope: global
- name: SSH - Deploy private key from Vault
copy:
content: "{{ vault_work_ssh_key }}"
dest: "~/.ssh/id_rsa_work"
mode: '0600'
This setup removes the cognitive load of switching contexts.
The system routes the correct key based on the host.