GitLab Deploy Keys instead of Access Tokens
I manage a large number of Git repositories across many nested Linux user environments running in rootless namespaces and container-like setups. Access to these environments is done via (e.g.)sudo machinectl shell codimd@ under restricted user contexts, which makes standard SSH workflows such as SSH agent forwarding unreliable or not possible at all.
As a result, maintaining access to Git remotes for frequent pushes becomes quite cumbersome. So far, I relied on personal access tokens hardcoded in HTTPS git origin URLs. I had to replace these tokens regularly, because they would expire after (e.g.) a year. Conversely, propagating the SSH authentication socket through isolated sessions proved difficult.
The solution for these contexts: Gitlab Deploy Keys. Don’t confuse this with Gitlab Deploy Tokens. Unlike tokens, deploy Keys are only available in projects, not groups. You can find project deploy keys under Project → Settings → Repository → Deploy Keys.
1. Generate SSH key
ssh-keygen -t ed25519 -f ~/.ssh/gitlab-deploy -N ""
2. Show public key
cat ~/.ssh/gitlab-deploy.pub
3. Add key in GitLab
Project → Settings → Repository → Deploy Keys
- Paste public key
- Enable: “Write access allowed”
- Add key
4. Configure git to use SSH key
This directly hooks your repo to the pecific deploy key:
git config core.sshCommand "ssh -i ~/.ssh/gitlab-deploy -o IdentitiesOnly=yes"
5. Switch repo remote to SSH
git remote set-url origin git@gitlab...:<group>/<repo>.git
6. Push test
git push