Skip to content

Automatically add an ssh key that can access all gitlab projects the user can access.

Description

While using any package manager you might need to use a private gitlab repo. For example, custom PHP, NPM, Ruby libraries. Currently (at least to the best of my knowledge) the only way to get this to work is to add an SSH key to the runner. This adds a lot of lines to .gitlab-ci.yml, as well as it's a bit of a security issue.

What I was able to find online had me doing the following:

  • Create an ssh key
  • Store the private key in a secret variable
  • Add the public key to ever private project as a deploy key
  • Add the following to .gitlab-ci.yml
before_script:
# install ssh-agent
- 'which ssh-agent || (apk add --update --no-cache openssh-client)'
# run ssh-agent
- 'eval $(ssh-agent -s)'
# add ssh key stored in SSH_PRIVATE_KEY variable to the agent store
- echo "$GITLAB_CI_SSH_KEY" > /tmp/gitlab_ci_ssh
- chmod 600 /tmp/gitlab_ci_ssh
- ssh-add /tmp/gitlab_ci_ssh
# disable host key checking (NOTE: makes you susceptible to man-in-the-middle attacks)
# WARNING: use only in docker container, if you use it with shell you will overwrite your user's ssh config
- mkdir -p ~/.ssh
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config

Proposal

Automatically add an SSH key in the runner that can access (read only) any repositories for the user who ran the pipeline.

Links / references

Edited by Alexander Kim