Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins : use withCredentials in global environment section

I have a Jenkins pipeline with multiple stages that all require the same environment variables, I run this like so:

script {
    withCredentials([usernamePassword(credentialsId: 'COMPOSER_REPO_MAGENTO', passwordVariable: 'MAGE_REPO_PASS', usernameVariable: 'MAGE_REPO_USER')]) {
        def composerAuth = """{
            "http-basic": {
                "repo.magento.com": {
                    "username": "${MAGE_REPO_USER}",
                    "password": "${MAGE_REPO_PASS}"
                }
            }
        }""";
        // do some stuff here that uses composerAuth
    }
}

I don't want to have to re-declare composerAuth every time, so I want to store the credentials in a global variable, so I can do something like:

script {
    // do some stuff here that uses global set composerAuth
}

I've tried putting it in the environment section:

environment {
    DOCKER_IMAGE_NAME = "magento2_website_sibo"
    withCredentials([usernamePassword(credentialsId: 'COMPOSER_REPO_MAGENTO', passwordVariable: 'MAGE_REPO_PASS', usernameVariable: 'MAGE_REPO_USER')]) {
        COMPOSER_AUTH = """{
            "http-basic": {
                "repo.magento.com": {
                    "username": "${MAGE_REPO_USER}",
                    "password": "${MAGE_REPO_PASS}"
                }
            }
        }""";
    }
}

But (groovy noob as I am) that doesn't work. So what's the best approach on setting a globally accessible variable with credentials but only have to declare it once?

like image 872
Giel Berkers Avatar asked Jan 10 '18 08:01

Giel Berkers


People also ask

What is Jenkins withCredentials?

withCredentials : Bind credentials to variables. Allows various kinds of credentials (secrets) to be used in idiosyncratic ways. ( Some steps explicitly ask for credentials of a particular kind, usually as a credentialsId parameter, in which case this step is unnecessary.)

How do I use Jenkins global credentials in shell script?

To use, first go to the Credentials link and add items of type Secret file and/or Secret text. Now in a freestyle job, check the box Use secret text(s) or file(s) and add some variable bindings which will use your credentials. The resulting environment variables can be accessed from shell script build steps and so on.


1 Answers

You can use credentials helper method of the environment section. For "Username and passwrd" type of credentials it assigns 2 additional environment variables. Example:

environment {
  MAGE_REPO_CREDENTIALS = credentials('COMPOSER_REPO_MAGENTO')
  COMPOSER_AUTH = """{
      "http-basic": {
          "repo.magento.com": {
              "username": "${env.MAGE_REPO_CREDENTIALS_USR}",
              "password": "${env.MAGE_REPO_CREDENTIALS_PSW}"
          }
      }
  }"""
}

Read more

like image 97
Artem Danilov Avatar answered Sep 22 '22 17:09

Artem Danilov