Prevent Jenkins job from building from another jenkins file

Viewed 35

We have 2 jenkins job AA and BB.

Is there a way to allow BB only to be trigger from AA after it completes?

1 Answers

Basically, you can use build triggers to do this. More about build triggers can be found here. There are two ways to add build triggers. Following is how you can add triggers using the UI. By going to Configure Job you can add triggers. Please refer to the following image.

enter image description here

In a declarative pipeline, you can add triggers as shown below.

pipeline {
    agent any
    triggers { upstream(upstreamProjects: 'AA', threshold: hudson.model.Result.SUCCESS) }

    stages {
        stage('Hello') {
            steps {
                echo 'Hello World BB'
            }
        }
    }
}

Here you can specify the threshold on when to trigger the build based on the status of the upstream build. There are 4 different thresholds.

  • hudson.model.Result.ABORTED: The upstream build was manually aborted.
  • hudson.model.Result.FAILURE: The upstream build had a fatal error.
  • hudson.model.Result.SUCCESS: The upstream build had no errors.
  • hudson.model.Result.UNSTABLE: The upstream build had an unstable result.

Update 02

If you want to restrict all other jobs/users from triggering this job you will have to restructure your Job. You can wrap your stages with a parent Stage and conditionally check who triggered the Job. But note that the Job will anyway trigger but the stages will be skipped. Please refer the following pipeline.

pipeline {
    agent any
    triggers { upstream(upstreamProjects: 'AA', threshold: hudson.model.Result.SUCCESS) }
    stages{
        stage('Parent') {
            // We will restrict triggering this Job for everyone other than Job AA
        when { expression { 
            print("Checking if the Trigger is allowed to execute this job")
            print('AA' in currentBuild.buildCauses.upstreamProject)
                } 
            }
            stages {
                stage('Hello') {
                    steps {
                        echo 'Hello World BB'
                    }
                }
            }
        }
    }
}
Related