0

Using a single declarative pipeline (not multibranch pipeline)

Is there a way I can trigger a certain stage only if its the Master Branch ?

I've been unsuccessful with the following:

Stage('Deploy') {
    steps {
        script {
            if (env.BRANCH_ENV == 'master') {
                sh "mvn deploy"
            } else {
                echo 'Ignoring'
            }
        }
    }
}

No matter what branch i'm deploying, everything gets ignored

any help or advice would be great

Victor Wong
  • 3,457
  • 1
  • 18
  • 31
stravze
  • 137
  • 3
  • 13
  • What I can gather, is the "When" condition is added, its only works under the MultiBranch Pipeline not the Single Pipeline setup – stravze Sep 06 '18 at 15:16

2 Answers2

0

I had the same issue before and figured that env.BRANCH_ENV does not return what I expected. You can echo env.BRANCH_ENV in your pipeline to confirm.

My solution to this was to get the git branch manually:

scmVars = checkout scm
gitBranch = sh(
    script: "echo ${scmVars.GIT_BRANCH} | cut -d '/' -f2",
    returnStdout: true
).trim()
Victor Wong
  • 3,457
  • 1
  • 18
  • 31
0

Here some approaches:

use return command to finalize prematurely the stage

https://stackoverflow.com/a/51406870/3957754

use when directive

when directive allows the Pipeline to determine whether the stage should be executed depending on the given condition

built-in conditions: branch, expression, allOf, anyOf, not etc.

when {
  // Execute the stage when the specified Groovy expression evaluates to true
  expression {
      return params.ENVIRONMENT ==~ /(?i)(STG|PRD)/
  }
}

Complete sample :

https://gist.github.com/HarshadRanganathan/97feed7f91b7ae542c994393447f3db4

JRichardsz
  • 14,356
  • 6
  • 59
  • 94