How to disable triggers from branch indexing but still allow SCM triggering in multibranch jobs
Asked Answered
D

8

7

When using a Jenkins Multibranch Pipeline Job if you choose Suppress Automatic SCM trigger in the job it will stop the job from building after indexing branches (great functionality).

However for some reason this ALSO will kill the ability to trigger the build from SCM events!

Is there any way to stop builds from triggering after branch discovery (branch indexing) but still build normally by SCM events?

Delogu answered 14/3, 2019 at 23:11 Comment(0)
D
8

You can always add logic to your pipeline to abort on branch indexing causes. For example:

  boolean isBranchIndexingCause() {
    def isBranchIndexing = false
    if (!currentBuild.rawBuild) {
      return true
    }

    currentBuild.rawBuild.getCauses().each { cause ->
      if (cause instanceof jenkins.branch.BranchIndexingCause) {
        isBranchIndexing = true
      }
    }
    return isBranchIndexing
  }

Adjust the logic to suit your use-case.

EDIT: The Pipeline Syntax > Global Variables Reference embedded within the Jenkins UI (e.g.: <jenkins url>/job/<pipeline job name>/pipeline-syntax/globals) has information about the currentBuild global variable, which lead to some javadocs:

The currentBuild variable, which is of type RunWrapper, may be used to refer to the currently running build. It has the following readable properties:

...

rawBuild:

a hudson.model.Run with further APIs, only for trusted libraries or administrator-approved scripts outside the sandbox; the value will not be Serializable so you may only access it inside a method marked @NonCPS

...

See also: jenkins.branch.BranchIndexingCause

Delinquent answered 26/6, 2019 at 14:49 Comment(1)
Seems like this is the right way to do it. Do you have any Jenkins documentation links for these method calls like rawBuild.getCauses() ? Looking through Jenkins docs not seeing these control mechanisms. I see blogs and tickets mentioning it but no docs. Thank you.Delogu
V
3

I know this post is very old, but maybe someone still has this issue, first you need to install the plugin basic-branch-build-strategies:

If you are using jenkins dsl:

buildStrategies {
  buildAllBranches {
    strategies {
      skipInitialBuildOnFirstBranchIndexing()
    }
  }
}
Valrievalry answered 12/12, 2020 at 21:56 Comment(0)
P
2

That's not the functionality for this - https://issues.jenkins-ci.org/browse/JENKINS-41980

Suppressing SCM Triggers should suppress all builds triggered by a detected change in the SCM irrespective of how the change was detected

Pewit answered 15/3, 2019 at 13:42 Comment(1)
I would like to disable the option, but I do not wants builds triggering by branch indexing. Is there a way to not trigger builds on branch indexing other than Suppress Automatic SCM trigger ?Delogu
D
2

There is a feature request for such functionality in the Jenkins backlog: JENKINS-63673 Allow configuring in NoTriggerBranchProperty which builds should be suppressed. I created a pull request today, so there is a chance it will be a part of the Branch API plugin in the future. In the meantime you may to use the custom version (see the build).

How to use the JobDSL plugin to configure it automatically:

multibranchPipelineJob {
    // ...

    branchSources {
        branchSource {
            source {
               // ...
            }
            strategy {
               allBranchesSame {
                    props {
                        suppressAutomaticTriggering  {
                            strategyId(2)
                        }
                    }
                }
            }
        }
    }

    // ...
}
Didymium answered 21/3, 2021 at 17:13 Comment(0)
P
2

Using @agabrys answer with modified suppressAutomaticTriggering props.

Set strategy to 'INDEXING' and triggeredBranchesRegex to the branches this would apply to - I just set it to '.*' (all branches) and specified branches in github source

multibranchPipelineJob {
    // ...

    branchSources {
        branchSource {
            source {
               // ...
            }
            strategy {
               allBranchesSame {
                    props {
                        suppressAutomaticTriggering  {
                            strategy('INDEXING')
                            triggeredBranchesRegex('.*')
                        }
                    }
                }
            }
        }
    }

    // ...
}

This assumes you have github plugin and Branch API plugin and of course job DSL plugin

Documentation for this specific property can be found in your Jenkins installation:

https://[YOUR JENKINS DOMAIN]/plugin/job-dsl/api-viewer/index.html#path/multibranchPipelineJob-branchSources-branchSource-strategy-allBranchesSame-props-suppressAutomaticTriggering

Pliocene answered 27/4, 2023 at 15:33 Comment(0)
G
1

For what I understand, this happens because the pipeline definition is not read when you set "Suppress Automatic SCM trigger".

And so, all triggers (SCM, upstream...) that you declared in the pipeline won't be known by Jenkins, until you run the job a first time.

So if you don't want builds to be triggered by branch indexing, set option "Suppress Automatic SCM trigger" If you want you pipeline to be known by Jenkins, so that he can react to your triggers, you should not set "Suppress Automatic SCM trigger"

Goglet answered 24/4, 2019 at 15:12 Comment(0)
W
0

We can Modify branch-api-plugin accordingly. https://github.com/jenkinsci/branch-api-plugin

here src/main/java/jenkins/branch/OverrideIndexTriggersJobProperty.java In this file it decides which Task to trigger Build

Here i have modified the function so that Feature branches are not triggered but will still be added to the list.

By Default it evaluates the checkbox Suppress Automatic SCM trigger

 @Extension
    public static class Dispatcher extends Queue.QueueDecisionHandler {

        private static final Logger LOGGER = Logger.getLogger(Dispatcher.class.getName());

        @SuppressWarnings("rawtypes") // untypable
        @Override
        public boolean shouldSchedule(Queue.Task p, List<Action> actions) {

                LOGGER.log(Level.INFO, "[TARUN_DEBUG] TASK NAME : "+ p.getName());
            if(p.getName().startsWith("feature")||p.getName().startsWith("bugfix")){
                return false;
            }
            else if(p.getName().startsWith("release")||p.getName().equals("master")||p.getName().startsWith("develop")||p.getName().startsWith("part of")||p.getName().startsWith("PR-")){
                
            }
            else{
                LOGGER.log(Level.INFO, "[TARUN_DEBUG] NOT TRIGGERED "+p.getName());
                return false;
            }

            for (Action action : actions) {
                if (action instanceof CauseAction) {
                    for (Cause c : ((CauseAction) action).getCauses()) {
                        if (c instanceof BranchIndexingCause) {
                            if (p instanceof Job) {
                                Job<?,?> j = (Job) p;
                                OverrideIndexTriggersJobProperty overrideProp = j.getProperty(OverrideIndexTriggersJobProperty.class);
                                if (overrideProp != null) {
                                    return overrideProp.getEnableTriggers();
                                } else {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }
Wrennie answered 13/6, 2021 at 8:7 Comment(0)
T
0

To skip a build triggered by build indexing you can place the following code snippet in your pipeline. No extra libraries required.

when {
    // Run pipeline/stage only if not triggered by branch indexing.
    not {
        triggeredBy 'BranchIndexingCause'
    }
}
Trappings answered 11/11, 2021 at 19:36 Comment(3)
Does it work on pipeline level?Saponin
@Saponin Works for pipeline and stages.Trappings
@AntohnyW would you share a minimum sample? It seems it doesn’t work on my end for declarative pipelines. Thanks!Saponin

© 2022 - 2024 — McMap. All rights reserved.