Jenkins : use withCredentials in global environment section Jenkins : use withCredentials in global environment section jenkins jenkins

Jenkins : use withCredentials in global environment section


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


After a lot of search (and struggle), i came up with an easy workaround:

As better explained in the jenkins docs for Handling Credentials, when injecting a usernamePassword type credential into an environment variable named VAR_NAME, jenkins automatically generates two other variables ending with _USR and _PSW respectively for usernameVariable and passwordVariable parameters.

What i did was to inject my variables with the values from both USR and PSW new variables.

In @Giel Berkers case, it should be something like this:

environment {    DOCKER_IMAGE_NAME = "magento2_website_sibo"    COMPOSER_REPO_MAGENTO_CREDENTIAL = credentials('COMPOSER_REPO_MAGENTO')    COMPOSER_AUTH = """{        "http-basic": {            "repo.magento.com": {                "username": "${COMPOSER_REPO_MAGENTO_CREDENTIAL_USR}",                "password": "${COMPOSER_REPO_MAGENTO_CREDENTIAL_PSW}"            }        }    }""";}


Here is how you can accomplish that

pipeline {    agent any    stages {        stage('first') {            steps {                script {                    withCredentials([usernamePassword(credentialsId: 'COMPOSER_REPO_MAGENTO', passwordVariable: 'MAGE_REPO_PASS', usernameVariable: 'MAGE_REPO_USER')]) {                        def user = env.MAGE_REPO_USER                        def password = env.MAGE_REPO_PASS                        //Initializing a global variable. Notice there is no def here                         composerAuth = """{                            "http-basic": {                                "repo.magento.com": {                                    "username": "${user}",                                    "password": "${password}"                                }                            }                        }"""                    }                }            }        }        stage('second') {            steps {                script {                    println composerAuth                }            }        }    }}