Skip to main content

GitLab SSH Authentication

Generate SSH Keypair

ssh-keygen -t ed25519 -C "gitlab-user@domain.tld" -f ~/.ssh/git-ssh-key

Enter your GitLab email address in the comment, if desired

cat ~/.ssh/git-ssh-key.pub

Output the public key string, which will be added in GitLab user profile

Add Public Key to GitLab

image.png

In the top-right, click on avatar > Edit profile > Access > SSH keys

image.png

Click on "Add new key"

image.png

As noted in the GUI, the expiration is optional. If you opt to expire the key, generate a new keypair with ssh-keygen as shown above and add a completely new key using the .pub string.

Configure SSH Agent

eval $(ssh-agent -s)

Start the SSH agent and export the environment variables using eval

 

echo -e '\neval $(ssh-agent -s) > /dev/null' >> "$HOME/.bashrc"

Add line to .bashrc to automatically start the SSH agent at login and export the environment variables

GITLAB_FQDN='gitlab-ce.lab.home.internal'
cat << EOF >> "$HOME/.ssh/config"

Host ${GITLAB_FQDN}
  AddKeysToAgent yes
  IdentityFile ~/.ssh/git-ssh-key
EOF

Add user SSH configuration with GitLab FQDN host match, causing SSH agent to handle authentication

Test SSH Authentication

Because we added eval $(ssh-agent -s) to the .bashrc file and sourced it in, the AddKeysToAgent yes configuration causes the SSH agent to use the IdentityFile whenever SSH public key authentication matches on the Host line -- in this case, gitlab-ce.lab.home.internal

GITLAB_FQDN='gitlab-ce.lab.home.internal'
ssh -T "git@${GITLAB_FQDN}"
GITLAB_FQDN='gitlab-ce.lab.home.internal'
GROUP='groupA'
REPO='testcode'
git clone "git@${GITLAB_FQDN}:${GROUP}/${REPO}.git"

Test git clone using SSH Agent