My repository remotes are set up to use deploy keys exclusively, as I don’t want to inadvertently push changes from the wrong account due to forgetting to change the local machine user’s credentials.
I used to do so by keeping several subdirectories inside my .ssh directory for per-account keys and manually pasting them outside whenever I want to push a specific repo, but it’s cumbersome and still quite error-prone.
Eventually I came across this SuperUser answer and adapted it with my slight twist leveraging the fact that the .git directory’s contents are well-behaved and don’t read or modify anything that Git doesn’t recognize, so no risk of accidentally committing keys.
Assuming the filenames of your private/public keypair are respectively id_ed25519 and id_ed25519.pub:
- Paste the private key file
id_ed25519into the .git directory of your current repo,
i.e. it should be located at<your-repo-name>/.git/id_ed25519now. - From your repository’s working directory, run in the terminal:
git config core.sshCommand "ssh -i .git/id_ed25519"
(Since SSH don’t actually care about the key’s filename, you can rename your keyfile to a more descriptive one as long as you reconfigure the sshCommand accordingly to refer to the right file)
Now anytime you push this repository to remote, it will use that private key file instead of the one located in your machine user’s .ssh directory.
This setup is localized to that repo and is entirely self-contained, i.e. you can move the repo to a different path or place it on a thumb drive to a different machine and it will work without reconfiguring.
First, set up local repository. Within the directory that is to be your repo:
git init
git config core.sshCommand "ssh -i .git/id_ed25519"
ssh-keygen -f .git/id_ed25519
After following the keygen prompts, if you open the .git directory, you will find the id_ed25519 and id_ed25519.pub private/public key files among other entries.
Open the id_ed25519.pub public key file and copy its contents. (or you could just print it in the console by typing cat .git/id_ed25519.pub)
Next, set up remote:
- create a new repository on GitHub/Codeberg/etc.
- go to repository settings -> Deploy Keys
- add deploy key, and paste the contents previously copied from the id_ed25519.pub file into the entry field.
Finally, copy the SSH clone address at the main web page of the repo, which should be something like [email protected]:<username>/<reponame>, and set it as remote for your local repository:
git remote add origin <ssh clone address>
git commit --allow-empty -m "My dummy commit to initialize repository"
git push -u origin
Note that I’ve made a dummy empty commit here just for the purpose of setting the upstream, but you can also just start working and only push with the -u flag to set upstream after you’ve committed to main.