How to pass credentials for jenkins to push a docker image to my own registry?

Jochen Gebsattel picture Jochen Gebsattel · Dec 9, 2019 · Viewed 13.5k times · Source

JHipster now uses the maven-jib-plugin. Before that, my jenkins server running in a docker-container was able to build a docker image with the *.war-file and push it to my own docker-registry with a pipeline using a 'Jenkinsfile' (for gradle, but I switched to Maven now), and after job completion another job pulled the newly build docker-image into a new docker-container on my server by executing shell scripts on the remote host using ssh.

The stages for this task were:

    def dockerImage
    stage('build docker') {
        sh "cp -Rvvv src/main/docker build/"
        sh "cp -vvv build/libs/*.war build/docker/"
        dockerImage = docker.build("$IMAGE_NAME:$IMAGE_TAG", "build/docker")
    }

    stage('publish docker') {
        docker.withRegistry("$REGISTRY_URL", "$REGISTRY_USER") {
            dockerImage.push "$IMAGE_TAG"
        }
    }

    stage('Remove Unused docker image') {
        sh "docker rmi $IMAGE_NAME:$IMAGE_TAG"
    }

Now as far as I can understand with jib making it easier and the relevant section in the Jenkinsfile produced with $ jhipster ci-cd it comes down to

    def dockerImage
    stage('publish docker') {
        sh "./mvnw -ntp jib:build -Dimage=$REGISTRY/$IMAGE_NAME:$IMAGE_TAG  -Djib.to.auth.username=$REGISTRY_USER"
    }

Unfortunately jib seems not to be using the credentials for the docker-registry user-login of the given $REGISTRY_USER any more which are saved in the Jenkins' 'credentials'-section as before with the docker daemon running in Jenkins.

How can I tell the jib-plugin in the jenkins pipeline to use the credentials for the docker-registry-login which are stored in my jenkins account, which I thought was/is a secure solution? I don't want the credentials - especially the password - to be handled on every client nor on github.

Answer

Chanseok Oh picture Chanseok Oh · Jan 13, 2020

One way to provide credentials through environment variables is to use withCredentials() in the following way, as hinted in this comment.

    def dockerImage
    stage('publish docker') {
        withCredentials([usernamePassword(credentialsId: 'myregistry-login', passwordVariable: 'DOCKER_REGISTRY_PWD', usernameVariable: 'DOCKER_REGISTRY_USER')]) {
            // assumes Jib is configured to use the environment variables
            sh "./mvnw -ntp jib:build"
        }
    }