Jenkins:在全局环境部分中使用withCredentials [英] Jenkins : use withCredentials in global environment section

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

问题描述

我有一个包含多个阶段的Jenkins管道,每个阶段都需要相同的环境变量,我这样运行:

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
    }
}

我不想每次都不必重新声明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?

推荐答案

您可以使用environment部分的credentials帮助方法.对于用户名和密码"类型的凭据,它会分配2个其他环境变量.示例:

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}"
          }
      }
  }"""
}

了解更多

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆