Uploaded image for project: 'Jenkins'
  1. Jenkins
  2. JENKINS-56850

When block outside of stage

XMLWordPrintable

      If you have a couple of microservices inside a single git repository and for each microservice there is a Jenkins Job sharing the same Jenkinsfile.  e. g. https://github.com/Xaseron/phippyandfriends

      The goal is that the pipeline for each microservice is only run if a change is made in the subdirectory or the build is triggered manually.

      The current possible solution is kind of ugly: (the job is multibranch pipeline named after the microservice e.g. captainkube)

      pipeline {
          options {
              timestamps()
          }
          agent {
              node {
                  label 'master'
              }
          }
          environment {
              /* get the foo out of e.g. foo/master */
              MICROSERVICE = "${env.JOB_NAME.tokenize('/')[0]}"
          }
          stages {
              /* useless stage to get the when block at the top level */
              stage('Meta') {
                  /* only start a build when something changed inside the microservice or it is triggered manually */
                  when {
                      anyOf {
                          triggeredBy cause: 'UserIdCause'
                          changeset "$MICROSERVICE/**"
                      }
                  }
                  stages {
                      stage('Build') {
                          steps {
                              echo "I've got a change in $MICROSERVICE"
                              echo "docker build -t $MICROSERVICE:$BUILD_NUMBER $MICROSERVICE"
                          }
                      }
                      stage('Test') {
                          steps {
                              echo 'test'
                          }
                      }
                      stage('Deploy') {
                          steps {
                              echo 'deploy'
                          }
                      }
                  }
              }
          }
      }
      

      The down side of this a approach is:

      • Meta stage for the when block (or the same when block in every stage)
      • every commit triggers a build even if there was no change in the subdirectory of the microservice

      One possible solution would be to allow the when block at the toplevel and don't start a build when it is not matched.

            Unassigned Unassigned
            xaseron Michael Werner
            Votes:
            3 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated: