Gie*_*ers 7 groovy credentials jenkins jenkins-pipeline
我有一个具有多个阶段的Jenkins管道,它们都需要相同的环境变量,我这样运行:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我不想composerAuth每次都重新声明,所以我想将凭证存储在全局变量中,所以我可以这样做:
script {
// do some stuff here that uses global set composerAuth
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试将它放在环境部分:
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}"
}
}
}""";
}
}
Run Code Online (Sandbox Code Playgroud)
但是(像我一样的groovy noob)不起作用.那么,使用凭证设置全局可访问变量的最佳方法是什么,但只需要声明一次?
小智 12
您可以使用credentials该environment部分的辅助方法。对于“用户名和密码”类型的凭据,它分配了 2 个额外的环境变量。例子:
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}"
}
}
}"""
}
Run Code Online (Sandbox Code Playgroud)
小智 8
经过大量搜索(和挣扎),我想出了一个简单的解决方法:
正如在詹金斯文档更好地解释为处理证书,注入时usernamePassword类型的凭证到名为的环境变量VAR_NAME,詹金斯自动生成与截至其它两个变量_USR和_PSW分别为usernameVariable和passwordVariable参数。
我所做的是将来自 USR 和 PSW 新变量的值注入我的变量。
在@Giel Berkers 的情况下,它应该是这样的:
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}"
}
}
}""";
}
Run Code Online (Sandbox Code Playgroud)
以下是实现这一目标的方法
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
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)