HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Jenkins Pipeline - input only if branch matches

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
matchesjenkinsinputbranchonlypipeline

Problem

I want to ask for input but only if we are on a certain branch. But the input is run before the when. Can this be done with declarative syntax?

For example this will always prompt even when the branch is not master

stage('only on master') {
   when {
      branch 'master'
   }
   input { ... }
}

Solution

I see two approaches :

Save current branch name on a variable and check it in a if statement

CURRENT_BRANCH = '...' // some value or parameter

stage('only on master') {
  if (CURRENT_BRANCH == 'master') {
  input {
    ...
  }
}

// be sure to check if input was set or define a default value


or

Run a shell script to know if current folder is a git repo on master

The following command check if current folder is a git repository printing "true" ( or returning a error if does not have repo)

git rev-parse --is-inside-work-tree


The next, print the current branch name

git branch | grep \* | cut -d ' ' -f2


Use both to create a script that sets an environment variable.
Check the value on your pipeline, to show the input

stage('only on master') {

  // Set true on IS_ON_MASTER if current branch is master, 
  // otherwise set false

  sh ./check-branch-master.sh 

  if (env.IS_ON_MASTER) {
  input {
    ...
  }
}

Code Snippets

CURRENT_BRANCH = '...' // some value or parameter

stage('only on master') {
  if (CURRENT_BRANCH == 'master') {
  input {
    ...
  }
}

// be sure to check if input was set or define a default value
git rev-parse --is-inside-work-tree
git branch | grep \* | cut -d ' ' -f2
stage('only on master') {

  // Set true on IS_ON_MASTER if current branch is master, 
  // otherwise set false

  sh ./check-branch-master.sh 

  if (env.IS_ON_MASTER) {
  input {
    ...
  }
}

Context

StackExchange DevOps Q#3951, answer score: 4

Revisions (0)

No revisions yet.