Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins declarative pipeline: Execute stage when file has changed or a new branch was created

I like to build a stage in a declarative pipeline only when certain files have changed. This can be achieved by the following pipeline:

pipeline {
  agent any

  stages {
    stage('checkout') {
        steps {
            checkout scm
        }
    }
    stage('build & push container') {
      when {
            anyOf {
                changeset 'Dockerfile'
            }
      }
      steps {
        echo "Building..."
      }
    }
  }
}

This does not build when a new branch is created as the changeset is still empty in Jenkins when a branch is built for the first time.

How can I define a when condition that builds the stage either when a certain files changes or a new branch is created?

like image 879
Tobias Getrost Avatar asked May 01 '18 08:05

Tobias Getrost


1 Answers

The following pipeline did the trick for me:

pipeline {
  agent any

  stages {
    stage('checkout') {
        steps {
            checkout scm
        }
    }
    stage('build & push container') {
      when {
            anyOf {
                changeset 'Dockerfile'
                expression {
                  return currentBuild.number == 1
                }
            }
      }
      steps {
        echo "Building..."
      }
    }
  }
}
like image 141
Tobias Getrost Avatar answered Sep 19 '22 23:09

Tobias Getrost