In jenkins declarative pipeline, how can I set environment variable based on method?
I had exactly the same problem, and indeed it is possible to use a shared library method. But there is another solution, more simple if you do not have a shared library set-up yet, that consists in defining a groovy method before the Pipeline statement and then use it inside your pipeline like this :
def getEnvFromBranch(branch) { if (branch == 'master') { return 'production' } else { return 'staging' }}pipeline { agent any environment { targetedEnv = getEnvFromBranch(env.BRANCH_NAME) } stages { stage('Build') { steps { echo "Building in ${env.targetedEnv}" } } }}
You can do exactly what you're suggesting. You should create a jenkins shared library with a var (a new DSL method). These can be called to assign to a pipeline-wide environment variable. You had it basically correct. Here's a Jenkinsfile fragment to assign to an environment variable:
environment { DEPLOY_ENV = mapBranchToDeployEnvironment()}
You don't need to pass the branch to the mapBranchToDeployEnvironment DSL method, since you can access the branch in that method. sample contents of vars/mapBranchToDeployEnvironment.groovy
in shared library look like this:
def call() { echo "branch is: ${env.BRANCH_NAME}" if (env.BRANCH_NAME == 'master') { return 'prod' } else { return 'staging' }}
You probably shouldn't expect this to be a five minute task, but you'll get it. Good luck!
stage('Prepare env variables') { steps { script { if (env.BRANCH_NAME == 'master') { echo 'Copying project-stg.env file...'; sh 'cp /opt/project-stg.env .env'; } else { echo 'Copying project-dev.env file...'; sh 'cp /opt/project-dev.env .env'; } } }}