首页 > 解决方案 > Jenkinsfile:如何根据分支名称参数化凭据 ID?

问题描述

我在我的 Jenkinsfile 中使用凭据插件,如下所示 -

stage("stage name"){
    steps{
        withCredentials([usernamePassword(credentialsId: 'credId', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
            sh'''
                statement 1
                statement 2
             '''
        }
    }
}

根据新要求,我需要根据分支名称使用不同的凭据 ID。这意味着如果分支名称是 master,我应该使用 credentialsId:'mastercred' 而对于其他分支,我应该使用 credentialsId:'othercred'。“withCredentials”块中的代码将是相同的,唯一的变化将是凭据Id。

我不想重复代码。有没有办法参数化这个credentialsId?

标签: jenkinsjenkins-pipelinejenkins-groovyjenkins-declarative-pipeline

解决方案


您可以读取分支名称变量,并将 acredentialId变量设置为在 withCredentials 上使用即可。例如:

stage("stage name"){
    steps{

        if (env.BRANCH_NAME == "master"){
            credentialId = "mastercred"
        }else
            credentialId = "othercred"
        }

        withCredentials([usernamePassword(credentialsId: "${credentialId}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
            sh'''
                statement 1
                statement 2
             '''
        }
    }
}


推荐阅读