How to dynamically pass credentialsId to Jenkins pipeline

Viewed 13129

Is there a way to dynamically pass the credentialsId in Jenkins pipeline within the withCredentials block using an environment variable?

Currently this works:

withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'my-aws-credentials',
                        ACCESS_KEY: 'ACCESS_KEY', SECRET_KEY: 'SECRET_KEY']]) { }

But this does not:

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

I should add that the builds runs within a docker container but other environment variables work fine, so I would expect this one to work too.

3 Answers

You can use combination of withEnv and withCredentials and pass the credentials dynamically. The credentials have to be defined in the Global credentials section within Jenkins using the Credentials Binding Plugin:

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



}
}

This worked for me. Hope this helps!!

Here is an example of how to set the credentialsId based on the value of the environment variable 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"
    }
}

Related