System Groovy scripts as a pre SCM build step, pre build step or post build step are an easy way extend the functionality of Jenkins without writing a complete Jenkins plugin.
In this blog post we will set the build description using two different techniques using the Groovy plugin.
Option 1: Using Build Parameters
In option one we use build parameters in the build description to set.
def currentBuild = Thread.currentThread().executable def variable1 = build.buildVariableResolver.resolve('variable1') def description = "$variable1" currentBuild.setDescription(description)
Option 2: Using Environment Variables
In option two we use environment variables in the build description to set.
def currentBuild = Thread.currentThread().executable def variable1 = build.getEnvironment(listener).get('variable1') def description = "$variable1" currentBuild.setDescription(description)
Example: Set the build description with a link back to an Atlassian Stash Pull Request build by a Jenkins job.
Here the URL to the Stash pull request (PULL_REQUEST_URL) and the id of the pull request (PULL_REQUEST_ID) are passed as parameters from Stash to Jenkins using the Pull Request Notifier for Stash add-on. A step-by-step how to integrate Stash and Jenkins for building pull requests can be found here.
def currentBuild = Thread.currentThread().executable def PULL_REQUEST_URL = build.buildVariableResolver.resolve('PULL_REQUEST_URL') def PULL_REQUEST_ID = build.buildVariableResolver.resolve('PULL_REQUEST_ID') def description = "<a href='$PULL_REQUEST_URL'>PR #$PULL_REQUEST_ID</a>" currentBuild.setDescription(description)
Pingback: Continuous Integration for Pull Requests with Jenkins and Stash | Code Addiction
What is the variable ‘build’?
I tried using the environment variable example but only received:
roovy.lang.MissingPropertyException: No such property: build for class: groovy.lang.Binding
Assuming ‘currentBuild’ should be ‘build’, we then hit a security sandbox blocker:
ERROR: Failed to evaluate groovy script.
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod java.lang.Thread currentThread
at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectStaticMethod(StaticWhitelist.java:192)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onStaticCall(SandboxInterceptor.java:142)