'How to Skip a stage in a jenkins pipeline Build based on a Jenkins trigger

Is there any way to skip certain stages after a GitLab webhook is triggered?

Here is my JenkinsFile:

enter image description here

and here are the triggers I set for this pipeline:

enter image description here

Now what I would like as a result is this:

1) For the 3rd stage (push docker image to docker registry) and 4th stage (check&run) to be skipped when the merge request is opened.

2) For the whole pipeline to run completely when the merge request is accepted.

I cannot seem to figure it out or any work-around to do it.

P.S : it shall be a simple pipeline project (I don't want to use a multi-branch project)



Solution 1:[1]

Build Cause is storred in hudson Cause class. What you can do is to add a script block to your declarative pipeline, get current build, get the Cause.

Cause is something like this, when viewed in basic jenkins UI:

enter image description here

Once you have the Cause you can do getShortDescription() on it to get the event that triggered the build. On base of that you can run your stages.

To get build causes from current build you need a scripted step like this:

script {
   def isMergeRequest = currentBuild.getBuildCauses()
}

Edit:

Apparently this can be done much easier, using the declarative built-in triggeredBy (official docs):

when { triggeredBy cause: "build-cause", detail: "detail" }

With this you don't need to extract the cause you can simply add it to your stage like this:

stage("trigger on condition") {

    when { triggeredBy cause: "UserIdCause", detail: "vlinde" }

    steps {
        ...some steps
    }
}

The cause should match something that is returned by scm when pull request is created and accepted (to fit your expectations).

Edit 2:

So since we didn't get the status in our triggeredBy cause, the only other thing I can think of is to use generic webhook plugin for Jenkins. It can be found here. It can parse the webhook payload and extract something from it using jsonpath, then set it as an env variable that we can use in pipeline script.

According to official docs gitlab merge request has this information in payload:

The available values for object_attributes.action in the payload are:

open, close, reopen, update, approved, unapproved, approval, unapproval, merge

So while using the generic webhook plugin you could extract the information about an event using this jsonpath:

object_attributes.action

set it to a variable name of your choice and based on that, run your stages.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1