Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.4k points)

I have the following use case: I would like to be able to push to [email protected]:gitolite-admin using the private key of user gitolite-admin, while I want to push to [email protected]:some_repo using 'my own' private key. AFAIK, I can't solve this using ~/.ssh/config, because the user name and server name are identical in both cases. As I mostly use my own private key, I have that defined in ~/.ssh/config for [email protected]. Does anyone know of a way to override the key that is used for a single git invocation?

(Aside: gitolite distinguishes who is doing the pushing based on the key, so it's not a problem, in terms of access, ownership, and auditing, that the user@server string is identical for different users.)

1 Answer

0 votes
by (27.5k points)

One way to resolve this is to use an alias that will run any git command, on any remote, with an alternative SSH key. The motive here is basically to switch your SSH identity when running the git commands.

In order to override the key that is used for a single git invocation you can follow the steps given below: 

Here we will be using a few small scripts and a git alias admin. 

$ git admin push 

In order too push to the default remote using the alternative ("admin") SSH key. Again, you could use any command (not just push) with this alias. You can even do git admin clone ... for cloning a repository that you would only have access to using your "admin" key.

First, create the alternative SSH keys, optionally set a passphrase in case you're doing this on someone else's machine.

Then create a script called “ssh-as.sh” that runs stuff that uses SSH, but uses a given SSH key rather than the default:

#!/bin/bash

exec ssh ${SSH_KEYFILE+-i "$SSH_KEYFILE"} "$@"

Again, create another script called “git-as.shthat runs git commands using the given SSH key.

#!/bin/bash

SSH_KEYFILE=$1 GIT_SSH=${BASH_SOURCE%/*}/ssh-as.sh exec git "${@:2}"

Now all you have to add an alias (using something appropriate for “PATH_TO_SCRIPTS_DIR” below):

# Run git commands as the SSH identity provided by the keyfile ~/.ssh/admin

$ git config --global alias.admin \!"PATH_TO_SCRIPTS_DIR/git-as.sh ~/.ssh/admin"

Related questions

Browse Categories

...