3
votes

I am running a VM in google cloud that runs a Jenkins server (within a docker container). I am trying to build a Docker image for my application and push it out to Google Container Registry using Jenkins pipeline.

  1. I installed all the required Jenkins plugins: Google OAuth Credentials Plugin, Docker Pipeline Plugin, Google Container Registry Auth Plugin

  2. Created a service account + key with Storage Admin and Object Viewer roles. Downloaded the json file.

  3. Created a credential in Jenkins using the google project name as the id and the json key.

  4. My pipeline code for build looks like this:

    stage('Build Image') {
        app = docker.build("<gcp-project-id>/<myproject>")
    }
    
  5. My pipeline code for build looks like this:

    stage('Push Image') {
    docker.withRegistry('https://us.gcr.io', 'gcr:<gcp-project-id>') {
        app.push("${commit_id}")
        app.push("latest")
    }
    

    }

However, the build fails at the last step with this error:

unauthorized: You don't have the needed permissions to perform this operation, and you may have invalid credentials. To authenticate your request, follow the steps in: https://cloud.google.com/container-registry/docs/advanced-authentication

I have spent several hours trying to figure this out. Any help would be greatly appreciated!

2

2 Answers

2
votes

I have an identical problem. I found out that Jenkins doesn't seem to use those credentials: Under usage it says 'This credential has not been recorded as used anywhere.' . When used with gcloud util, the service account and key work fine, so the problem is somewhere in Jenkins.

2
votes

Create a service account in GCP with permission to push image and then copy the credential json fie and save it as credentials inside Jenkins; call in the credentials id inside your pipeline like below and it should push images to gcr

            withCredentials([file(credentialsId: 'gcr', variable: 'GC_KEY')]){
              sh "cat '$GC_KEY' | docker login -u _json_key --password-stdin https://eu.gcr.io"
              sh "gcloud auth activate-service-account --key-file='$GC_KEY'"
              sh "gcloud auth configure-docker"
              GLOUD_AUTH = sh (
                    script: 'gcloud auth print-access-token',
                    returnStdout: true
                ).trim()
              echo "Pushing image To GCR"
              sh "docker push eu.gcr.io/${google_projectname}/${image_name}:${image-tag}"
          }

Additionally i have defined some variables used above