user3575337
user3575337

Reputation: 192

How to dynamically pass credentialsId to Jenkins pipeline

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.

Upvotes: 8

Views: 20676

Answers (4)

Islam Salah
Islam Salah

Reputation: 2156

I tried to to set the credentialsId based on the value of the environment variable and it worked fine using env.VAR_NAME:

stage('PrintProd packages'){
               env.KUBECONFIG='development-kubeconfig'
                withCredentials([file(credentialsId: env.KUBECONFIG, variable: 'KUBECRED')]) 
    {
    `enter code here`sh 'helm  list  --kubeconfig=$KUBECRED'
    
    }

Upvotes: 0

Joman68
Joman68

Reputation: 2850

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

Upvotes: 1

anuj0901
anuj0901

Reputation: 593

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!!

Upvotes: 2

user3575337
user3575337

Reputation: 192

Actually, I was able to solve it by doing this ->

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

Upvotes: 3

Related Questions