Skip to content

Instantly share code, notes, and snippets.

@genericpenguin
Forked from jasonk/Jenkinsfile
Last active December 9, 2020 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genericpenguin/fba3ad50a346d2627d611d650f696a8e to your computer and use it in GitHub Desktop.
Save genericpenguin/fba3ad50a346d2627d611d650f696a8e to your computer and use it in GitHub Desktop.
Docker credential helper for authenticating from environment variables

docker-credential-env

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 Jenkins).

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

{ "credsStore": "env" }

To use it, you need to have the following environment variables set:

DOCKER_REGISTRY - Your registry URL
DOCKER_CREDS_USR - Your username
DOCKER_CREDS_PSW - Your password

If you are using Jenkins Declarative Pipeline, you can do this in the environment section of your Jenkinsfile (see the example Jenkinsfile).

{ "credsStore": "env" }
#!/bin/bash
# docker-credential-env
# 2018 - Jason Kohles
# Requires three environment variables:
# DOCKER_REGISTRY - the URL of the docker registry.
# DOCKER_CREDS_USR - username to access with registry.
# DOCKER_CREDS_PSW - the password for the username.
REG="${DOCKER_REGISTRY#https://}"
REG="${REG%%/*}"
die() {
echo "$@" 1>&2
exit 1
}
if [ -z "$REG" ]; then die "DOCKER_REGISTRY not set in environment"; fi
case "$1" in
get)
read HOST
if [ "$HOST" = "$REG" ]; then
printf '{"ServerURL":"%s","Username":"%q","Secret":"%q"}\n' \
"$HOST" "$DOCKER_CREDS_USR" "$DOCKER_CREDS_PSW"
else
die "No credentials available for $HOST"
fi
;;
list)
printf '{"%s":"%q"}\n' \
"$REG" "$DOCKER_CREDS_USR"
;;
*)
die "Unsupported operation"
;;
esac
pipeline {
environment {
DOCKER_REGISTRY = 'https://my-docker-registry.example.com'
DOCKER_CREDS = credentials( 'my-docker-credentials' )
}
}
@genericpenguin
Copy link
Author

Added list option to docker-credential-env to allow newer libraries to not fail when accessing the "store".

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