groovy 如何将credentialsId动态传递到Jenkins管道

scyqe7ek  于 2023-03-01  发布在  Jenkins
关注(0)|答案(4)|浏览(188)

有没有办法使用环境变量在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容器中运行,但是其他环境变量工作正常,所以我希望这个环境变量也能工作。

q1qsirdb

q1qsirdb1#

实际上,我可以这样来解决它-〉

withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.AWS_CREDENTIAL_ID,
                        ACCESS_KEY: 'ACCESS_KEY', SECRET_KEY: 'SECRET_KEY']]) { }
eagi6jfj

eagi6jfj2#

您可以使用withEnv和withCredentials的组合并动态传递凭据。凭据必须使用凭据绑定插件在Jenkins的全局凭据部分中定义:

withEnv([""CREDENTIALID=pw_${<some global variable>}",]) {
withCredentials([string(credentialsId: "${CREDENTIALID}", variable: 'mypassword' )]) {


}
}

这对我很有效。希望这对我有帮助!!

fdbelqdn

fdbelqdn3#

以下示例说明如何根据环境变量DEPLOYMENT_ENVIRONMENT的值设置credentialsId:

#! 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"
    }
}
kmynzznz

kmynzznz4#

我尝试使用下面的代码根据环境变量的值设置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'
    
    }

相关问题