Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Jenkinsfile: How to get the trigger of a build

Writer Matthew Martinez

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?

4

3 Answers

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 "" }
}
1
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

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.