9

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?

Tobias Getrost
  • 191
  • 1
  • 7

1 Answers1

10

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..."
      }
    }
  }
}
Tobias Getrost
  • 191
  • 1
  • 7
  • Is there any way to get a changeset listing the differences from the parent branch? E.g. If I've just created a new branch and edited the `/README.md` file, I don't want to run any tests, so I added `changeset '/src'`, but the above code will still run an hour of tests on the first build. – PFudd Mar 10 '23 at 19:01
  • The Jenkins team is aware of this, and due to the complexity of Git, they don't intend to fix it, because there is no universally-correct way to determine the right parent to compare with: issues.jenkins.io/browse/JENKINS-26354 – PFudd Mar 10 '23 at 19:30