Jenkins Build Pipeline fileLoad in library files not working - jenkins

I'm using the Workflow Remote Loader plugin's fileLoad function to load dependencies for my build script. In my main file, I have the following:
build-app.groovy
def java
def util
node {
stage "Setup"
fileLoader.withGit('git#github.com:myorg/build-scripts.git', 'master', '234720asdf8ed1a2', '') {
java = fileLoader.load('lib/java.groovy');
util = fileLoader.load('lib/util.groovy');
}
util.checkIfFileExists('myFile.txt')
def version = java.getJarVersion("api")
}
util.checkIfFileExists() works perfectly, but a problem occurs when java.getJarVersion is called. In getJarVersion there is also a dependency on util. My java lib is as follows:
java.groovy
def util = fileLoader.load('lib/util.groovy')
def getJarVersion() {
...
util.checkIfFileExists('myFile.txt')
...
}
This gives the following error when I run in Jenkins:
groovy.lang.MissingPropertyException: No such property: util for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:62)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:224)
at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:23)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:17)
at Script4.checkIfFileExists(Script4.groovy:39)
at Script4.getJarVersion(Script4.groovy:23)
at WorkflowScript.run(WorkflowScript:18)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:62)
at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:54)
at sun.reflect.GeneratedMethodAccessor254.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:32)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:29)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:29)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:276)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$000(CpsThreadGroup.java:78)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:185)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:183)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
The plugin's doc says:
Use static initializers within the Groovy file of the loaded file to
load more context from neighbor files.
I've tried static def util = fileLoader.load('lib/util.groovy'), but this produced the same error. I've also tried a variety of other combinations to no avail. Maybe this is some lack of understanding of the groovy language? Not really sure.
Thanks in advance!

For those coming here from Google on a similar error message, you have to install the Pipeline Remote Loader plugin. Otherwise it will give you:
groovy.lang.MissingPropertyException: No such property: fileLoader for class: groovy.lang.Binding

OK, after much trial and error, I figured out the issue.
java.groovy before:
def util = fileLoader.load('lib/util.groovy')
def getJarVersion() {
...
util.checkIfFileExists('myFile.txt')
...
}
return this;
java.groovy after:
def getJarVersion() {
...
util.checkIfFileExists('myFile.txt')
...
}
this.util = fileLoader.load('lib/util.groovy')
return this;
The return this; line was omitted from the original post because it was in the documentation of the remote file loader plugin, but it's key. When java.groovy is loaded from build.groovy it is using the returned this as the scope the calls made to java.groovy. This scope did not include util when it was defined as def util = fileLoader.load('lib/util.groovy'). Adding it to this before returning it put util in scope for all function calls in the file.

Related

Dynamic Parallel stages in Jenkins Pipeline outside 'script' block

I am trying to construct parallel stages dynamically, as demonstrated here and here. Specifically, I am trying to do this in a function defined outside the scope of the pipeline, e.g.:
pipeline{
stages{
stage('CI'){
steps{
doDynamicParallelSteps()
}
}
}
}
def doDynamicParallelSteps(){
tests = [:]
for (f in findFiles(glob: '**/html/*.html')) {
tests["${f}"] = {
node {
stage("${f}") {
echo '${f}'
}
}
}
}
parallel tests
}
The problem is, it seems this only works when the dynamic parallel generation code is inside a script{} block within the steps{} block of the pipeline (as seen in the first source).
When running something similar to the code snippet above, I see this error in jenkins:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.lang.String.call() is applicable for argument types: (java.lang.String, org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [teststage, org.jenkinsci.plugins.workflow.cps.CpsClosure2#2e1b48b4]
Possible solutions: wait(), any(), trim(), size(), next(), size()
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:153)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:155)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:159)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
at WorkflowScript.parallelHandler(WorkflowScript:1383)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:57)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:109)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:82)
at sun.reflect.GeneratedMethodAccessor110.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ClosureBlock.eval(ClosureBlock.java:46)
at com.cloudbees.groovy.cps.Next.step(Next.java:83)
at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:122)
at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:261)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$101(SandboxContinuable.java:34)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.lambda$run0$0(SandboxContinuable.java:59)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:58)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:182)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:332)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:83)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:244)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:232)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE
Is there any way to have it defined as a function in the way I showed in the initial code snippet, or am I stuck with having a ton of script{} blocks in my pipeline definition?
The declarative pipeline does not allow you to put Groovy code inside steps {} block - it expects a valid Jenkins pipeline step in this place. This is why script {} block got introduced that can be put inside the steps {} block to execute some Groovy code.
If you need flexibility and non-opinionated syntax then you might use scripted pipeline instead. Here you can mix Groovy code with existing pipeline steps with almost no limitations.
Jenkins documentation explains shortly the difference between both approaches and why they exist:
When Jenkins Pipeline was first created, Groovy was selected as the foundation. Jenkins has long shipped with an embedded Groovy engine to provide advanced scripting capabilities for admins and users alike. Additionally, the implementors of Jenkins Pipeline found Groovy to be a solid foundation upon which to build what is now referred to as the "Scripted Pipeline" DSL. [2].
As it is a fully featured programming environment, Scripted Pipeline offers a tremendous amount of flexibility and extensibility to Jenkins users. The Groovy learning-curve isn’t typically desirable for all members of a given team, so Declarative Pipeline was created to offer a simpler and more opinionated syntax for authoring Jenkins Pipeline.
Both are fundamentally the same Pipeline sub-system underneath. They are both durable implementations of "Pipeline as code." They are both able to use steps built into Pipeline or provided by plugins. Both are able to utilize Shared Libraries
Your example in scripted pipeline may look like this:
node {
stage('CI') {
doDynamicParallelSteps()
}
}
def doDynamicParallelSteps(){
tests = [:]
for (f in findFiles(glob: '**/html/*.html')) {
tests["${f}"] = {
node {
stage("${f}") {
echo '${f}'
}
}
}
}
parallel tests
}
And declarative pipeline with script {} block in steps would look like this:
pipeline{
agent any
stages{
stage('CI'){
steps{
script {
doDynamicParallelSteps()
}
}
}
}
}
def doDynamicParallelSteps(){
tests = [:]
for (f in findFiles(glob: '**/html/*.html')) {
tests["${f}"] = {
node {
stage("${f}") {
echo '${f}'
}
}
}
}
parallel tests
}

How do I solve "Expected named arguments" for freeStyleJob?

I have several different projects that will be compiled in Jenkins and shall be uploaded to my Nexus3 repository. For that I am using the NexusArtifcalUploader. For some reason I get the following error message although the code is essentially copied from the plugin page of the Jenkins wiki.
java.lang.IllegalArgumentException: Expected named arguments but got [clientmoduleNexusArtifactUploaderJob, org.jenkinsci.plugins.workflow.cps.CpsClosure2#63d801fc]
at org.jenkinsci.plugins.workflow.cps.DSL.parseArgs(DSL.java:511)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeDescribable(DSL.java:291)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:153)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:108)
at sun.reflect.GeneratedMethodAccessor463.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
...
My Jenkinsfile calls the uploadToNexus method I created which creates freeStyleJobs:
def uploadToNexus(module) {
def groupId = "com.example"
def moduleVersions = [
"client-module": "1.0.0-SNAPSHOT",
"server-module": "1.0.0-SNAPSHOT",
]
def moduleVersion = moduleVersions.get(module)
def jobName = "${fixModuleName(module)}NexusArtifactUploaderJob"
echo "will run freeStyleJob ${jobName} now..."
freeStyleJob(jobName) {
steps {
nexusArtifactUploader {
nexusVersion('nexus3')
protocol('http')
nexusUrl('nexus:8081')
groupId(groupId)
version(moduleVersion)
repository('maven2_central')
credentialsId('nexus_admin')
artifact {
artifactId('${module}')
type('war')
classifier('debug')
file('${module}.war')
}
}
}
}
}
To my knowledge freeStyleJob expects a string which I pass, don't I? What am I missing and doing wrong?
It seems that I mixed up Job DSL and Pipeline DSL. I wasn't aware there's a difference.
Here's a way to use Job DSL inside Pipeline DSL:
https://github.com/jenkinsci/job-dsl-plugin/wiki/User-Power-Moves#use-job-dsl-in-pipeline-scripts

Parsing an XML file within a Jenkins pipeline

Note:
I posted this question back when I only had a master node in my Jenkins environment. This made serialization a lesser issue as there were no other nodes to communicate with, thus the code here will not run as expected on a multi-node environment (for instance, readFile will only read files from the master node).
In my experience it's better to have your configuration written in other formats (JSON, YAML, Groovy which are all supported natively in Jenkins), or use external tools (such as xmllint on Linux) if you don't have control over the file's format.
Original question:
I have an XML file which I'd like to use as input for a pipeline script. Problem is the XMLParser isn't serializable so I put it in a NonCPS function, but I lost the Node object because of that.
This is the pipeline script:
def buildPlanPath = 'C:\\buildPlan_test.xml'
#NonCPS
groovy.util.Node getBuildPlan(path) {
new XmlParser().parseText(readFile(path))
}
node {
//def buildPlan = new XmlParser().parseText(readFile(buildPlanPath))
groovy.util.Node buildPlan = getBuildPlan(buildPlanPath)
println buildPlan.getClass()
println buildPlan
println buildPlan.branch
}
This is an input sample:
<branch name='mybranch'>
<stage>
<job name='job11' />
<job name='job12' />
</stage>
<stage>
<job name='job21' />
<job name='job22' />
<job name='job23' />
</stage>
<stage>
<job name='job31' />
</stage>
</branch>
This is the result:
Started by user admin
[Pipeline] node
Running on master in C:\Jenkins\workspace\pipeline-develop
[Pipeline] {
[Pipeline] readFile
[Pipeline] echo
class java.lang.String
[Pipeline] echo
<branch name='mybranch'>
<stage>
<job name='job11' />
<job name='job12' />
</stage>
<stage>
<job name='job21' />
<job name='job22' />
<job name='job23' />
</stage>
<stage>
<job name='job31' />
</stage>
</branch>
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: branch for class: java.lang.String
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:25)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:17)
at WorkflowScript.run(WorkflowScript:16)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:62)
at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:54)
at sun.reflect.GeneratedMethodAccessor327.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:276)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$000(CpsThreadGroup.java:78)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:185)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:183)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
at java.util.concurrent.FutureTask.run(Unknown Source)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Finished: FAILURE
I'm using Jenkins 2.7 with pipeline 2.1, which are currently the latest.
You could use XmlSlurper, it works for me.
def xmlText = new XmlSlurper().parse(MyURL)
xmlText.data.artifact.each {******
As branch is the root element, you don't need to explicitly specify it when accessing your parsed nodes
Try changing
println buildPlan.branch
To
println buildPlan.stage
To print out the stage nodes
A #NonCPS method should only accept or return Serializable types. Try returning .branch from the method.
May I recommend a shared library. That will allow you to
centralize logic
write unit tests - via jenkins pipeline unit and perhaps Spock
use this kind of approach
Src dir
class PipelineSupport {
PipelineSupport(def env, def jenkinsStepAccess) {
this.env = env
this.jenkinsStepAccess = jenkinsStepAccess
}
def readXml(def path) {
def text = jenkinsStepAccess.readFile(path)
def parser = new XmlParser()
def xml = parser.parseText(text.toString())
return xml
}
}
vars dir var/foo.groovy
import ...PipelineSupport
Map readXml(def path) {
// pass env and "this" access point to jenkins DSL to calls
return new PipelineSupport(env, this).readXml(path)
}
use in a build
library "mylib"
def xmlData = foo.readXml('path/to/bar.xml')
In the end I think my approach was wrong: I decided to convert the XML file into a separate groovy script and load it within the pipeline
Update: Recently people started editing my answer for clarity, but the fact is that I just ditched storing my configuration in XML files and opted for groovy scripts, which gave me more flexibility. I understand it may not be a common practice, but it suits my needs.
For example - instead of:
config.xml:
<settings>
<floopi>2</floopi>
</settings>
I used:
config.groovy:
[
floopi: 2
]
And in the pipeline script:
stage('init') {
def settings = load('config.groovy')
echo "floopi: ${settings.floopi}"
}
I hope that's a better answer :)

How to add build parameters to jenkins multibranch pipeline?

I would like to add additional build parameters to my jenkins mutibranch pipeline job.
Relevant versions:
org.jenkins-ci.plugins:script-security:1.19
org.kohsuke:groovy-sandbox:1.10
org.jenkins-ci.main:jenkins-war:2.0
org.jenkins-ci.plugins.workflow:workflow-aggregator:2.0
My Jenkins file:
As you can see the first four lines are supposed to add the build parameter option.
import hudson.model.*
def build = Thread.currentThread().executable;
build.addAction(new ParametersAction(new StringParameterValue("SVN_UPSTREAM", build.getEnvVars()['SVN_REVISION'])));
println "SVN_UPSTREAM:" + build.getEnvVars()['SVN_UPSTREAM'];
node('dockerSlave') {
stage 'Checkout'
checkout scm
def mvnHome = tool 'M3'
stage 'VersionSet'
def v = version()
if (v) {
echo "Building version ${v}"
}
sh "${mvnHome}/bin/mvn versions:set -DnewVersion=${env.BUILD_NUMBER}"
stage 'Build'
sshagent(['601b6ce9-37f7-439a-ac0b-8e368947d98d']) {
sh 'echo SSH_AUTH_SOCK=$SSH_AUTH_SOCK'
sh "${mvnHome}/bin/mvn -B -Dmaven.test.failure.ignore clean deploy scm:tag"
step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
}
}
def version() {
def matcher = readFile('pom.xml') =~ '<version>(.+)</version>'
matcher ? matcher[0][1] : null
}
Unfortunately i get the following error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:
Scripts not permitted to use staticMethod java.lang.Thread
currentThread at
Is there a way to add the static method to a whitelist or add a build parameter via a different way?
[Pipeline] End of Pipeline
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:174)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onStaticCall(SandboxInterceptor.java:142)
at org.kohsuke.groovy.sandbox.impl.Checker$2.call(Checker.java:180)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedStaticCall(Checker.java:177)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:91)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:15)
at WorkflowScript.run(WorkflowScript:2)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:55)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:106)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixName(FunctionCallBlock.java:74)
at sun.reflect.GeneratedMethodAccessor210.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:19)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:277)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$000(CpsThreadGroup.java:77)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:186)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:184)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Finished: FAILURE
Update:
Seems like disabling the sandbox mode is not possible at the moment.
https://cloudbees.zendesk.com/hc/en-us/articles/207406207-Avoid-script-approvals-with-a-Jenkins-Pipeline-Groovy-script
You should use properties step. Also take a look here at Stackoverflow: How do I use jenkins pipeline properties step?. That is my question where I've learned that you need to explicitly add parentheses even though snippet generator doesn't do that.
Example:
properties([[$class: 'ParametersDefinitionProperty', parameterDefinitions: [[$class: 'StringParameterDefinition', name: 'myparam', defaultValue: 'default value']]]])
echo "received ${binding.hasVariable('myparam') ? myparam : 'undefined'}"

Jenkins: Groovy No signature of method: static hudson.model.Job.getBuildDir()

I am using Jenkins 1.6.20 testing the Workflow Plugin which uses Groovy for creating the job as you would know.
I am trying to get information about the current job, for example the working directory of the job.
This is my code:
import hudson.EnvVars
import hudson.model.*
def build_number = Job.getBuildDir()
echo "$build_number"
It gives me the error:
groovy.lang.MissingMethodException: No signature of method: static hudson.model.Job.getBuildDir() is applicable for argument types: () values: []
Possible solutions: getBuildDir(), getBuilds(), getBuild(java.lang.String), getBuilds(hudson.model.Fingerprint$RangeSet), getRootDir()
at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1367)
at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1353)
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:50)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:15)
at WorkflowScript.run(WorkflowScript:4)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:69)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:106)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixName(FunctionCallBlock.java:74)
at sun.reflect.GeneratedMethodAccessor1418.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
Using this documentation:
http://javadoc.jenkins-ci.org/hudson/model/Job.html
I can read that the method getBuildDir is actually there and also the error suggest me to use getBuildDir making no sense for me.
If it is useful for someone I could get the workspace dir by:
node {
def pwdv = pwd()
echo "path ${pwdv}"
}

Resources