Search code examples
jenkinsjenkins-pipelinejenkins-groovyjenkins-declarative-pipeline

Jenkinsfile: How to parameterise Credential Id as per branch name?


I am using credentials plugin in my Jenkinsfile like below-

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

As per new requirement, I need to different credentials id as per branch name. That means if branch name is master, I should use credentialsId:'mastercred' and for other branches, I should use credentialsId:'othercred'. The code in "withCredentials" block will be the same for, the only change will be with credentialsId.

I don't want to duplicate code. Is there any way to parameterise this credentialsId?


Solution

  • You can read the branch name variable, and set the a credentialId variable to use on withCredentials would the work. For example:

    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
                 '''
            }
        }
    }