How to authenticate with a Google Service Account in Jenkins pipeline

12,475

Solution 1

You need to upload your Sevice Account JSON file as a secret file. Then:

withCredentials([file(credentialsId: 'key-sa', variable: 'GC_KEY')]) {
    sh("gcloud auth activate-service-account --key-file=${GC_KEY}")
    sh("gcloud container clusters get-credentials prod --zone northamerica-northeast1-a --project ${project}")
  }

Solution 2

I couldn't get the 'Google Service Account from private key' working, but using the 'Secret File' type of credential in Jenkins, and uploaded my google service account JSON works.

Share:
12,475

Related videos on Youtube

stefanbuck
Author by

stefanbuck

Updated on June 07, 2022

Comments

  • stefanbuck
    stefanbuck almost 2 years

    I want to use gcloud in Jenkins pipeline and therefore I have to authenticate first with the Google Service account. I'm using the https://wiki.jenkins.io/display/JENKINS/Google+OAuth+Plugin which holds my Private Key Credentials. I'm stuck with loading the credentials into the pipeline:

    withCredentials([[$class: 'MultiBinding', credentialsId: 'my-creds', variable: 'GCSKEY']]) {
        sh "gcloud auth activate-service-account --key-file=${GCSKEY}"
    }
    

    I also tried it with from file, but without luck.

    withCredentials([file(credentialsId:'my-creds', variable: 'GCSKEY')]) {
    

    The log says:

    org.jenkinsci.plugins.credentialsbinding.impl.CredentialNotFoundException: Credentials 'my-creds' is of type 'Google Service Account from private key' ....
    
  • Shailyn Ortiz
    Shailyn Ortiz over 5 years
    Why can't I upvote every time I read this? @stackoverflow plz
  • Sagi
    Sagi over 5 years
    Please make it bolder and clearer that JSON file should be uploaded as a secret file and not as a google service account
  • Grubhart
    Grubhart almost 4 years
    it works to me too, but I should use. '${GC_KEY}' .
  • Ares91
    Ares91 over 3 years
    I got this: ERROR: (gcloud.auth.activate-service-account) There was a problem refreshing your current auth tokens: ('invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values in the JWT claim.',