本文介绍了Jenkins:在全局环境部分使用 withCredentials的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

解决方案

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

这篇关于Jenkins:在全局环境部分使用 withCredentials的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 17:46