Jenkins pipeline stages with conditions

755 Views Asked by At

Can I use "jenkins job builder" and create pipeline job, which I could run only specific stages in? Something like this:

pipeline:
    if (condition):
       stage1:
           //... 
    if (condition):
       stage2:
           //...

or

pipeline:
    stage1:
       if (condition):
           //... 
    stage2:
       if (condition):
           //...
2

There are 2 best solutions below

0
On

You could use something like this, I hope this helps

stage ('build') {
  when {
    expression { condition() }
  }
  steps {
    sh "mvn clean package "
  }
}

stage ('build') {
  when {
    expression { condition() }
  }
  steps {
    sh "mvn clean install"
  }
}
0
On

Yes, you can add conditions in your Jenkinsfile. You have to define all your stages, and inside you add condition (like your second example). You can use the when expression to do this : https://www.jenkins.io/doc/book/pipeline/syntax/#when