6

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 { ... }
}
4

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 {
    ...
  }
}
  • Don't forget to add closing bracket "}", which are missing in the first and last code snippets. – Chris Apr 10 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.