gpt4 book ai didi

jenkins - 如何在 Jenkins 声明式管道的所有阶段获取 Jenkins 凭据变量

转载 作者:行者123 更新时间:2023-12-02 03:09:34 32 4
gpt4 key购买 nike

如何获取 Jenkins 凭证变量,即“mysqlpassword”,可供 Jenkins 声明性管道的所有阶段访问?

下面的代码片段工作正常并打印我的凭据。

node {
stage('Getting Database Credentials') {
withCredentials([usernamePassword(credentialsId: 'mysql_creds', passwordVariable: 'mysqlpassword', usernameVariable: 'mysqlusername')])
{
creds = "\nUsername: ${mysqlusername}\nPassword: ${mysqlpassword}\n"
}
println creds
}
}

如何将上述代码合并到当前管道中,以便管道脚本中的所有阶段(即全局)都可以访问 mysqlusername 和 mysqlpassword 变量。

我的管道脚本布局如下所示:

pipeline {          //indicate the job is written in Declarative Pipeline

agent { label 'Prod_Slave' }

environment {
STAGE_2_EXECUTED = "0"
}

stages {
stage ("First Stage") {
steps {
echo "First called in pipeline"
script {
echo "Inside script of First stage"
}

}
} // end of first stage

stage ("Second Stage") {
steps {
echo "Second stage called in pipeline"
script {
echo "Inside script of Second stage"
}

}
} // end of second stage

} //end of stages
} // end of pipeline

我使用的是最新版本的 Jenkins。

请求解决方案。谢谢。

最佳答案

你可以做这样的事情。在这里,您可以在 environment { } 下定义变量,并在整个阶段中使用它。

pipeline {
agent any
environment {
// More detail:
// https://jenkins.io/doc/book/pipeline/jenkinsfile/#usernames-and-passwords
MYSQL_CRED = credentials('mysql_creds')
}
stages {
stage('Run Some Command') {
steps{
echo "Running some command"
sh '<some-command> -u $MYSQL_CRED_USR -p $MYSQL_CRED_PSW'
}
}
}

环境下定义的变量对于所有阶段都是全局的,因此可以在整个 jenkinsfile 中使用。

有关 official documentation 中的 credentials() 的更多信息.

关于jenkins - 如何在 Jenkins 声明式管道的所有阶段获取 Jenkins 凭据变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58037858/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com