有没有办法使用环境变量在 withCredentials 块内动态传递 Jenkins 管道中的 credentialsId?
目前这个作品:
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'my-aws-credentials',
ACCESS_KEY: 'ACCESS_KEY', SECRET_KEY: 'SECRET_KEY']]) { }
但这不是:
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: '${AWS_CREDENTIAL_ID}',
ACCESS_KEY: 'ACCESS_KEY', SECRET_KEY: 'SECRET_KEY']]) { }
我应该补充一点,构建在 docker 容器中运行,但其他环境变量工作正常,所以我希望这个也能工作。
实际上,我可以通过这样做来解决它->
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CREDENTIAL_ID,
ACCESS_KEY: 'ACCESS_KEY', SECRET_KEY: 'SECRET_KEY']]) { }
您可以结合使用 withEnv 和 withCredentials 并动态传递凭据。凭据必须使用凭据绑定插件在 Jenkins 的全局凭据部分中定义:
withEnv([""CREDENTIALID=pw_${<some global variable>}",]) {
withCredentials([string(credentialsId: "${CREDENTIALID}", variable: 'mypassword' )]) {
}
}
这对我有用。希望这有帮助!
这里举例说明如何根据环境变量的值设置credentialsId
DEPLOYMENT_ENVIRONMENT
:
#! groovy
pipeline {
environment {
CREDENTIALS_ID = getCredentialsId()
}
stages {
stage('Build') {
steps {
withCredentials([string(credentialsId: "${CREDENTIALS_ID}", variable: 'password')]) {
bat """gradlew build -Dpassword=$password"""
}
}
}
}
}
String getCredentialsId() {
if (env.DEPLOYMENT_ENVIRONMENT == "PRODUCTION") {
"prodPassword"
} else {
"defaultPassword"
}
}
我尝试使用以下代码根据环境变量的值设置 credentialsId 但我没有工作:
stage('PrintProd packages'){
env.KUBECONFIG='development-kubeconfig'
withCredentials([file(credentialsId: env.KUBECONFIG, variable: 'KUBECRED')])
{
`enter code here`sh 'helm list --kubeconfig=$KUBECRED'
}
使用 env.variable 效果很好:
stage('PrintProd packages'){
env.KUBECONFIG='development-kubeconfig'
withCredentials([file(credentialsId: env.KUBECONFIG, variable: 'KUBECRED')])
{
`enter code here`sh 'helm list --kubeconfig=$KUBECRED'
}