Clone Using GitHub Deploy Keys
When cloning repositories on remote servers, it is recommended not to use your personal credentials, as this makes all your repositories accessible to anyone with access to the server.
Instead, use GitHub Deploy Keys to clone the repositories from GitHub.
Using a separate GitHub account ("machine user") for cloning can also lead to security issues if not managed properly. Using deploy keys is a better alternative.
Follow these steps to clone a repository from GitHub using deploy keys:
- Create a new SSH key pair on the remote server
ssh-keygen -t ed25519 -f "$HOME/.ssh/github-clone-xyz-repo" -C "$(whoami)@$(hostname)" -P ""
(Replace xyz-repo in the key name above with your repo name)
- Add the public key of the newly created key pair to the GitHub repo as a Deploy Key in GitHub repo > Settings > Deploy Keys > Add
cat ~/.ssh/github-clone-xyz-repo.pub
- Clone using the Deploy Key
GIT_SSH_COMMAND='ssh -i ~/.ssh/github-clone-xyz-repo -o IdentitiesOnly=yes' git clone <SSH REMOTE URL>
(Use the GitHub SSH remote URL in place of <SSH REMOTE URL>)
- Set the repo to always use the Deploy Key when fetching
cd repo-dir
git config core.sshCommand 'ssh -i ~/.ssh/github-clone-xyz-repo -o IdentitiesOnly=yes'
git fetch
Deploy keys have access to a single repository. You'll need to create a new deploy key for each repository you want to clone. You can, however, use the same deploy key on multiple servers to clone that repo.