Daniel
Daniel

Reputation: 35724

Define branch-specific environment variables in Jenkinsfile

I'd like to pass environment variables by publish stage based on the branch that the multi-pipeline job is processing.

While this example below works, I don't like how I'm ending up with additional stages, one per branch. Because I'm using the withCredentials plugin, I need to have the MY_CREDENTIALS variable set before that block. Is there a more elegant approach to solve this?


pipeline {
    agent {
        dockerfile true
    }
    stages {
        
        stage("Config vars for staging") {
            when {
                branch 'staging'
            }
            environment { 
                MY_CREDENTIALS = 'creds-staging'
                MY_ENVIRONMENT = 'production'
            }
            steps {
                sh "echo MY_ENVIRONMENT: $MY_ENVIRONMENT"
            }
        }

        stage("Config vars for production") {
            when {
                branch 'master'
            }
            environment { 
                MY_CREDENTIALS = 'creds-prod'
                MY_ENVIRONMENT = 'staging'
            }
            steps {
                sh "echo MY_ENVIRONMENT: $MY_ENVIRONMENT"
            }
        }

        stage("Publish") {
            steps {
                withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.MY_CREDENTIALS, accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY']]) {
                    sh 'make takecareofit'
                }   
            }
        }
    }
}

Upvotes: 1

Views: 1811

Answers (1)

Sers
Sers

Reputation: 12255

Use switch statement. In example below I forced FAILURE if branch is not master or staging:

pipeline {
    agent {
        dockerfile true
    }
    stages {
        stage("Config vars") {
            steps {
                script {
                    switch(branch) { 
                        case 'staging': 
                            MY_CREDENTIALS = 'creds-staging'
                            MY_ENVIRONMENT = 'production'
                            break
                        case "master": 
                            MY_CREDENTIALS = 'creds-prod'
                            MY_ENVIRONMENT = 'staging' 
                            break
                       default:
                            println("Branch value error: " + branch)
                            currentBuild.getRawBuild().getExecutor().interrupt(Result.FAILURE)
                    }
                }
            }
        }
        stage("Publish") {
            steps {
                withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: env.MY_CREDENTIALS, accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY']]) {
                    sh 'make takecareofit'
                }
            }
        }
    }
}

Upvotes: 2

Related Questions