ewok
ewok

Reputation: 21503

Jenkinsfile: How to get the trigger of a build

I'm trying to figure out how to determine what caused a build to run from inside a scripted Jenkinsfile. The reason is that I have a script in a docker container that I want to run on a cron job, so when the cron job triggers, I just want it to run the container, but when I push changes, I want it check out the code, rebuild the container, run static code analysis, run tests, etc. There's no need for all of that on a cron run.

How can I get the cause? I tried currentBuild.getCauses(), but I get

groovy.lang.MissingMethodException: No signature of method: org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper.getCauses() is applicable for argument types: () values: []

I tried println currentBuild.getRawBuild().getCauses(), but got

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getRawBuild

How cna i get the cause of a build in my jenkinsfile?

Upvotes: 3

Views: 7481

Answers (3)

Joman68
Joman68

Reputation: 2850

This Groovy code will get the name of the triggering project (and it runs fine in the Groovy sandbox):

String getTriggeringProjectName() {
    if (currentBuild.upstreamBuilds) {
        return currentBuild.upstreamBuilds[0].projectName
    } else {
        return ""
    }
}

Upvotes: 3

John Jones
John Jones

Reputation: 2043

The project name of the triggering build (getUpstreamProject) and the build number (getUpstreamBuild):

currentBuild.rawBuild.getCauses().get(0).getUpstreamProject()
currentBuild.rawBuild.getCauses().get(0).getUpstreamBuild()

Or another way that I think might not need permissions changes: currentBuild.getUpstreamBuilds().get(0).getProjectName()

I needed the upstream project's branch in something I'm working on:

currentBuild.getUpstreamBuilds().get(0).getRawBuild().getEnvVars().get("BRANCH_NAME", "")

Here's the docs on that: getEnvVars()

You'll have to enable a mess of permissions, by the way.

Upvotes: 1

Simkin
Simkin

Reputation: 180

manager.build.causes

for use, you will need to approve these signatures

method org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder$BadgeManager getBuild
method hudson.model.Run getCauses

hope it helps

Upvotes: 1

Related Questions