Conditionally selecting credentials in withcredentials in jenkins

Viewed 313

I have a jenkins stage which requires different credentials based on some parameters. The contents stays the same for each stage, the only change is the credentials, so I could achieve this by just having multiple stages with single credentials then just using those, but obviously not ideal.

I'm trying it essentially like this but jenkins doesn't like it

        stage('test execute') {
            steps {
                withCredentials([
                    if (params.Env == 'env1') {
                        usernamePassword(credentialsId: 'creds1', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')
                    } else if (params.Env == 'env2') {
                        usernamePassword(credentialsId: 'creds2', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')
                    }
                ]) 
            }
        }

I get the below error though

WorkflowScript: 25: unexpected token: if @ line 25, column 21.
                       if (params.Env == 'env1') {
                       ^

so I'm not sure if there's any way to add conditional logic to withcredentials, or if I just have to have multiple stages with essentially the same code

1 Answers

I got around this by storing the credentialsId in an environment variable, and then using that env variable in the usernamePassword() statement.

def getDeploymentCreds(envName)
{
    switch(envName) {
        case ~/^Dev/: return 'MY_DEV_CREDS'
        case ~/^QA/: return 'MY_QA_CREDS'
        case ~/^Beta/: return 'MY_BETA_CREDS'
    }
}

// ...

script {
    env.DEPLOY_CREDS_ID = getDeploymentCreds(env.TARGET_ENVIRONMENT)
}

// ...

withCredentials([
    usernamePassword(credentialsId: env.DEPLOY_CREDS_ID, passwordVariable: 'DEPLOY_PASS', usernameVariable: 'DEPLOY_USER')
])
Related