Skip to content

Instantly share code, notes, and snippets.

@ap-wtioit
Forked from jasonk/Jenkinsfile
Last active June 27, 2022 03:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ap-wtioit/5e8379a1acc74affffe15f754ef1f6e1 to your computer and use it in GitHub Desktop.
Save ap-wtioit/5e8379a1acc74affffe15f754ef1f6e1 to your computer and use it in GitHub Desktop.
Docker credential helper for authenticating from environment variables

docker-credential-gitlab_runner

This is a very basic Docker credential helper that uses environment variables to authenticate to Docker. It's not as secure as the other credential helpers that Docker provides, but it can be very helpful in some circumstances (such as when using it with Gitlab CI).

To set this up, install the docker-credentials-gitlab_runner script somewhere in the Gitlab runner users path (it needs to be named docker-credential-gitlab_runner), then configure the Gitlab runner user's ~/.docker/config.json file to use it:

{ "credsStore": "gitlab_runner" }

you also need to have the following environment variables set:

CI_REGISTRY - Your registry URL
CI_REGISTRY_USER - Your username
CI_REGISTRY_PASSWORD - Your password

which should already be set for the job if you are using Gitlab runner, see https://docs.gitlab.com/ee/ci/variables/predefined_variables.html

This is based on https://gist.github.com/jasonk/480d87b49e4c8caf51932f184ff764b2 from @jasonk

{ "credsStore": "gitlab_runner" }
#!/bin/bash
# docker-credential-gitlab_runner
# 2018 - Jason Kohles
# 2021 - Andreas Perhab
REG="${CI_REGISTRY#https://}"
REG="${REG%%/*}"
die() {
echo "$@" 1>&2
exit 1
}
if [ -z "$REG" ]; then die "CI_REGISTRY not set in environment"; fi
case "$1" in
get)
read HOST
if [[ "$HOST" == "$REG" || "$HOST" == "" ]] ; then
printf '{"ServerURL":"%s","Username":"%q","Secret":"%q"}\n' \
"$REG" "$CI_REGISTRY_USER" "$CI_REGISTRY_PASSWORD"
else
# this exact message needs to be sent on stdout otherwhise docker-compose build fail when checking credentials for https://index.docker.io/v1/
echo "credentials not found in native keychain"
exit 1
fi
;;
list)
printf '{"%s":"%q"}' "$REG" "$CI_REGISTRY_USER"
;;
store)
echo "store is ignored in docker-credential-gitlab_runner, we are still using the gitlab ci env variables for docker" 1>&2
;;
*)
die "Unsupported operation: $1"
;;
esac
@temoto
Copy link

temoto commented Jun 27, 2022

Thank you! This should be gitlab-runner default behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment