Jenkins Pipelines - Global library support cannot recognise vars - jenkins

I have followed instructions from here in order to add some global functions to my Jenkins Pipelines. I followed the directory structure provided and I load my code through an external git repository not the one provided by Jenkins itself. Although I can add some functions under src directory and are loaded correctly as explained, I cannot load the scripts added under vars directory. Is there any way to understand what is happening. My example groovy script is very simple:
// vars/hello.groovy
def call(name) {
echo "Hello world, ${name}"
}
and i try to invoke it as follows
hello "foo"
I get the following:
> java.lang.NoSuchMethodError: No such DSL method 'hello' found among
> [archive, bat, build, catchError, checkout, deleteDir, dir, echo,
> error, fileExists, git, input, isUnix, load, mail, node, parallel,
> properties, pwd, readFile, retry, sh, sleep, stage, stash, step, svn,
> timeout, tool, unarchive, unstash, waitUntil, withEnv, wrap,
> writeFile, ws] at
> org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:107) at
> org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:113)
> at groovy.lang.GroovyObject$invokeMethod.call(Unknown Source) at
> org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
> at
> org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
> at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:151)
>
>
>
Has anyone faced any similar issue and how I can debug what is going on?
My Jenkins version is: 1.625.2
EDIT#1:
After as well reading this indeed after a restart the script works, but this is not efficient to restart on each change. Is there any other solution to load the vars/*.groovy scripts without a restart?

Related

Getting error after Jenkins update: java.lang.NoSuchMethodError: No such DSL method 'pipeline' found among steps

My Jenkins pipeline is failing after I updated by Jenkins version from 2.224 to 2.234 along with all the plugins to the latest version.
Below is my pipeline script which was working fine with older Jenkins and older plugins.
With Jenkins and plugin update, the pipeline is failing.
pipeline {
agent none
stages {
stage ("Check Parameters") {
steps {
echo "In pipeline"
script {
echo "Start condition check"
}
}
}
}
}
The above is just a sample as the actual pipeline script is quite vast and I did not wish to confuse the readers.
I get the following Error when i run the pipeline
[Pipeline] Start of Pipeline
[Pipeline] End of Pipeline
java.lang.NoSuchMethodError: No such DSL method 'pipeline' found among steps [ansiColor, ansiblePlaybook, ansibleTower, ansibleTowerProjectRevision, ansibleTowerProjectSync, ansibleVault, archive, bat, catchError, checkout, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, dockerNode, echo, emailext, emailextrecipients, error, fileExists, findBuildScans, getContext, git, input, isUnix, junit, library, libraryResource, load, lock, mail, node, parallel, powershell, properties, publishHTML, pwd, pwsh, readFile, readTrusted, resolveScm, retry, sh, sleep, stage, stash, step, svn, task, timeout, tm, tool, unarchive, unstable, unstash, waitUntil, warnError, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, withGradle, wrap, writeFile, ws] or symbols [all, always, ant, antFromApache, antOutcome, antTarget, apiToken, architecture, archiveArtifacts, artifactManager, attach, authorizationMatrix, batchFile, booleanParam, brokenBuildSuspects, brokenTestsSuspects, buildButton, buildDiscarder, buildDiscarders, buildFailureAnalyzer, caseInsensitive, caseSensitive, certificate, choice, choiceParam, cleanWs, clock, command, credentials, cron, crumb, cssText, cssUrl, culprits, defaultFolderConfiguration, defaultView, demand, developers, disableConcurrentBuilds, disableResume, docker, dockerCert, dockerfile, downstream, dumb, durabilityHint, envInject, envVars, faviconUrl, file, fileParam, filePath, fingerprint, frameOptions, freeStyle, freeStyleJob, fromScm, fromSource, ftpPublisher, git, gitBranchDiscovery, gitHubBranchDiscovery, gitHubBranchHeadAuthority, gitHubExcludeArchivedRepositories, gitHubForkDiscovery, gitHubPullRequestDiscovery, gitHubSshCheckout, gitHubTagDiscovery, gitHubTrustContributors, gitHubTrustEveryone, gitHubTrustNobody, gitHubTrustPermissions, gitParameter, gitTagDiscovery, github, githubPush, gradle, headRegexFilter, headWildcardFilter, hyperlink, hyperlinkToModels, inheriting, inheritingGlobal, installSource, jdk, jdkInstaller, jgit, jgitapache, jnlp, jobBuildDiscarder, jobName, jsUrl, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logRotator, loggedInUsersCanDoAnything, mailer, masterBuild, maven, maven3Mojos, mavenErrors, mavenMojos, mavenWarnings, modernSCM, myView, newContainerPerStage, nodeProperties, nonInheriting, none, overrideIndexTriggers, paneStatus, parameterizedCron, parameters, password, pattern, permanent, pipeline-model, pipeline-model-docker, pipelineTriggers, plainText, plugin, pollSCM, projectNamingStrategy, proxy, queueItemAuthenticator, quietPeriod, rateLimitBuilds, recipients, requestor, resourceRoot, run, runParam, sSHLauncher, schedule, scmRetryCount, scriptApproval, scriptApprovalLink, search, security, shell, simple-theme-plugin, simpleBuildDiscarder, slave, sourceRegexFilter, sourceWildcardFilter, ssh, sshPublicKey, sshPublisher, sshPublisherDesc, sshTransfer, sshUserPrivateKey, standard, status, string, stringParam, swapSpace, teamSlugFilter, text, textParam, timezone, tmpSpace, toolLocation, unsecured, upstream, upstreamDevelopers, userSeed, usernameColonPassword, usernamePassword, validatingString, viewsTabBar, weather, withAnt, zfs, zip] or globals [currentBuild, docker, env, params, scm]
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:202)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
at sun.reflect.GeneratedMethodAccessor232.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:163)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:157)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:142)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:161)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:165)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
at WorkflowScript.run(WorkflowScript:1)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
at sun.reflect.GeneratedMethodAccessor231.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:129)
at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:400)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:96)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:312)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:276)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
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
The current updated latest versions of pipeline plugin showing under Installed tab of Plugin Manager is below:
The one thing that I see missing that was visible earlier under installed plugins is Pipeline: version 2.6
Upon my research I downloaded https://plugins.jenkins.io/workflow-aggregator/ hpi file, however, when i install this plugin in offline mode it tried to pull dependencies like Pipeline Milestone Step etc.
Is getting this hpi file and its dependencies installed the solution to my problem? Please clarify.
Build Pipeline Plugin
This plugin renders upstream and downstream connected jobs that typically form a build pipeline. In addition, it offers the ability to define manual triggers for jobs that require intervention prior to execution, e.g. an approval process outside of Jenkins.
1.5.8
Delivery Pipeline Plugin
This plugin visualize Delivery Pipelines (Jobs with upstream/downstream dependencies)
1.4.2
Pipeline Graph Analysis Plugin
Provides a REST API to access pipeline and pipeline run data.
1.10
Pipeline: API
Plugin that defines Pipeline API.
2.40
Pipeline: Basic Steps
Commonly used steps for Pipelines.
2.20
Pipeline: Declarative Extension Points API
APIs for extension points used in Declarative Pipelines.
1.6.0
Pipeline: GitHub Groovy Libraries
Allows Pipeline Grrovy libraries to be loaded on the fly from GitHub.
1.0
Pipeline: Groovy
Pipeline execution engine based on continuation passing style transformation of Groovy scripts.
2.80
Pipeline: Input Step
Adds the Pipeline step input to wait for human input or approval.
2.11
Pipeline: Job
Defines a new job type for pipelines and provides their generic user interface.
2.39
Pipeline: Model API
Model API for Declarative Pipeline.
1.6.0
Pipeline: Multibranch
Enhances Pipeline plugin to handle branches better by automatically grouping builds from different branches.
2.21
Pipeline: Nodes and Processes
Pipeline steps locking agents and workspaces, and running external processes that may survive a Jenkins restart or slave reconnection.
2.35
Pipeline: REST API Plugin
Provides a REST API to access pipeline and pipeline run data.
2.13
Pipeline: SCM Step
Adds a Pipeline step to check out or update working sources from various SCMs (version control).
2.11
Pipeline: Shared Groovy Libraries
Shared libraries for Pipeline scripts.
2.16
Pipeline: Stage Step
Adds the Pipeline step stage to delineate portions of a build.
2.3
Pipeline: Stage View Plugin
Pipeline Stage View Plugin.
2.13
Pipeline: Step API
API for asynchronous build step primitive.
2.22
Pipeline: Supporting APIs
Common utility implementations to build Pipeline Plugin
3.4
I do not have internet connectivity and I have to copy the plugins manually.
I do see the downgrade button next to a few plugins. However, do not wish to downgrade due to vulnerability and bug fixes.
Can you please suggest some solution, please?
The issue was pipeline plugin was not installed. Thus I downloaded the pipeline plugin version 2.6
https://plugins.jenkins.io/workflow-aggregator/
I then downloaded the dependencies as below:
https://www.jenkins.io/doc/pipeline/steps/pipeline-build-step/
https://updates.jenkins.io/download/plugins/pipeline-milestone-step/
https://plugins.jenkins.io/pipeline-model-definition/
https://plugins.jenkins.io/pipeline-model-declarative-agent/
https://plugins.jenkins.io/pipeline-stage-tags-metadata/
Installed them one by one in offline mode and the issue was resolved.
In my case the Ansible plugin was installed, but there were some security issues which was causing the issue. I updated the Ansible plugin, restarted the Jenkins, executed the pipeline job and it worked.
If you have plugin installed, please check in Manage Jenkins section that is there any security warning which needs resolution.
You need to check is Ansible enabled.
Navigate to Manage Jenkins -> Manage Plugins -> Installed and check "Ansible Plugin" is enabled.
If it's not, then enable it and press the restart button at the bottom.
Last step is to Configure Ansible
Go to Manage Jenkins -> Global tool configuration
Scroll down and go to Ansible section and click "Ansible installations..."
In Name field, set any name you want
In Path to Ansible executables directory set "/usr/bin/" (For Ubuntu)
To get the path of Ansible installation use $ which ansible in terminal

"Scripts not permitted to use field hudson.util.Secret value" when passing a password parameter to a downstream job in a Jenkinsfile [duplicate]

I am Using Jenkins 2 for compiling Java Projects, I want to read the version from a pom.xml, I was following this example:
https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md
The example suggest:
It seems that there is some security problem accessing the File System but I can't figure out what it is giving (or why) that problem:
I am just doing a little bit different than the example:
def version() {
String path = pwd();
def matcher = readFile("${path}/pom.xml") =~ '<version>(.+)</version>'
return matcher ? matcher[0][1] : null
}
The Error I am getting when running the 'version' method :
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object (org.codehaus.groovy.runtime.GStringImpl call org.codehaus.groovy.runtime.GStringImpl)
at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:165)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:117)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:103)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:15)
at WorkflowScript.run(WorkflowScript:71)
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.fixArg(FunctionCallBlock.java:79)
at sun.reflect.GeneratedMethodAccessor408.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.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:100)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:79)
at sun.reflect.GeneratedMethodAccessor408.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.ContinuationGroup.methodCall(ContinuationGroup.java:57)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:106)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:79)
at sun.reflect.GeneratedMethodAccessor408.invoke(Unknown Source)
I am using these versions:
Plugin Pipeline 2.1
Jenkins 2.2
Quickfix Solution:
I had similar issue and I resolved it doing the following
Navigate to jenkins > Manage jenkins > In-process Script Approval
There was a pending command, which I had to approve.
Alternative 1: Disable sandbox
As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.
Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script:
Alternative 2: Disable script security
As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:
-Dpermissive-script-security.enabled=true
So you jenkins.xml will look something like this:
<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>
Make sure you know what you are doing if you implement this!
You have to disable the sandbox for Groovy in your job configuration.
Currently this is not possible for multibranch projects where the groovy script comes from the scm. For more information see https://issues.jenkins-ci.org/browse/JENKINS-28178
I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.
Example:
myvar1 = userInput['param1']
myvar2 = userInput['param2']
to:
myvar = userInput
To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):
import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"
evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)
in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.
To get the version of a maven project, I usually use mvn binary in the sh block as follows. No need for admin permissions.
stage("Compile") {
steps {
sh """
mvn help:evaluate -Dexpression=project.version -q -DforceStdout > version.txt
"""
}
}
Following #JavaTechnical's answer herein a Maven project's version can be assigend to a variable:
stage("getPomProjectVersion") {
steps {
...
def pomProjectVersion = sh script: 'mvn help:evaluate -Dexpression=project.version -q -DforceStdout', returnStdout: true
...
}
}
The issue I had was that the Groovy object didn't have the function I was attempting to call. To my understanding if Groovy can't find the function then Groovy starts to do introspection on the object looking for for the undefined object, which caused this error.
So check to make sure that the function you are trying to call really exists.
Unrelated to OP's issue; But this Stack Overflow Question pops up on top of search.
I was getting this error when I tried to declare a variable named owner (re-declare apparently) in my pipeline script. Changed it to repoOwner and the script worked as expected.

Quality Gate status with Jenkins pipeline not working

While checking quality gate status in pipeine, getting following error.
Pipeline Code is below
stage('SonarQube') {
// Run the maven build
dir("xyz_7.6_Trunk/xyz-services"){
sh ' mvn -f pom.xml clean install -Dapp.server=jboss org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar -Dsonar.host.url=http://10.11.135.66:9000 -Dsonar.scm.disabled=True -U'
}
}
stage('Quality Gate') {
timeout(time: 1, unit: ‘HOURS’) {
def qg = waitForQualityGate()
if (qg.status != ‘OK’) {
error “Pipeline aborted due to quality gate failure: ${qg.status}”
}
}
}
Error log is below.
java.lang.NoSuchMethodError: No such DSL method 'Time' 'HOURS' found among steps [acceptGitLabMR, addBadge, addErrorBadge, addGitLabMRComment, addHtmlBadge, addInfoBadge, addShortText, addWarningBadge, ansiblePlaybook, ansibleTower, ansibleVault, archive, artifactPromotion, bat, build, catchError, checkout, createSummary, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, dockerNode, ec2, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, getContext, git, gitChangelog, gitlabBuilds, gitlabCommitStatus, input, isUnix, junit, library, libraryResource, load, mail, milestone, nexusArtifactUploader, nexusPolicyEvaluation, nexusPublisher, node, parallel, powershell, properties, pwd, readFile, readTrusted, removeBadges,
As I see, you use scripted pipeline, so the syntax should be fine.
timeout functionality is implemented in Pipeline: Basic Steps plugin (part of Pipeline plugin). That's why I think that you need to reinstall those plugins and the issue should be fixed. Anyway, please check again the syntax of the timeout step.

Running groovy script at the end of Jenkins Job

I need to run a groovy Post-Build script to do some clean up so I have arranged the following script:
def sout = new StringBuilder(), serr = new StringBuilder()
def proc = '/usr/bin/docker stop mysql'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
Although the command '/usr/bin/docker stop mysql' works if I log on the machine, when the groovy script is executed, the following error is raised:
java.io.IOException: Cannot run program "/usr/bin/docker": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at java.lang.Runtime.exec(Runtime.java:620)
at java.lang.Runtime.exec(Runtime.java:450)
at java.lang.Runtime.exec(Runtime.java:347)
at org.codehaus.groovy.runtime.ProcessGroovyMethods.execute(ProcessGroovyMethods.java:533)
at org.codehaus.groovy.runtime.dgm$894.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:274)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:157)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:104)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:155)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:159)
at org.kohsuke.groovy.sandbox.impl.Checker$checkedCall$0.callStatic(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:56)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:194)
at Script1.run(Script1.groovy:2)
Do you know why the groovy engine fails to find the 'docker' command?
Thanks!
The Groovy Postbuild plugin actually runs on the master, not on the build node. The documentation states:
This plugin executes a groovy script in the Jenkins JVM
which is presumably meant to convey "and not in an agent JVM". (Fun side note: If you use println in the Groovy script, it prints out to the Jenkins master log, not to the job's console log)
The Post build task plugin does run on the build node (and you don't need to wrap your shell command in a groovy script). The task requires a condition: to "always run" your script just leave the Log text blank.
You might also consider taking a look at the Jenkins Pipeline, which lets you bake in try/catch type logic and maintain your pipeline "as code" using a Jenkinsfile.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

I am Using Jenkins 2 for compiling Java Projects, I want to read the version from a pom.xml, I was following this example:
https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md
The example suggest:
It seems that there is some security problem accessing the File System but I can't figure out what it is giving (or why) that problem:
I am just doing a little bit different than the example:
def version() {
String path = pwd();
def matcher = readFile("${path}/pom.xml") =~ '<version>(.+)</version>'
return matcher ? matcher[0][1] : null
}
The Error I am getting when running the 'version' method :
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object (org.codehaus.groovy.runtime.GStringImpl call org.codehaus.groovy.runtime.GStringImpl)
at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:165)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:117)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:103)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:15)
at WorkflowScript.run(WorkflowScript:71)
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.fixArg(FunctionCallBlock.java:79)
at sun.reflect.GeneratedMethodAccessor408.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.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:100)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:79)
at sun.reflect.GeneratedMethodAccessor408.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.ContinuationGroup.methodCall(ContinuationGroup.java:57)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:106)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:79)
at sun.reflect.GeneratedMethodAccessor408.invoke(Unknown Source)
I am using these versions:
Plugin Pipeline 2.1
Jenkins 2.2
Quickfix Solution:
I had similar issue and I resolved it doing the following
Navigate to jenkins > Manage jenkins > In-process Script Approval
There was a pending command, which I had to approve.
Alternative 1: Disable sandbox
As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.
Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script:
Alternative 2: Disable script security
As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:
-Dpermissive-script-security.enabled=true
So you jenkins.xml will look something like this:
<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>
Make sure you know what you are doing if you implement this!
You have to disable the sandbox for Groovy in your job configuration.
Currently this is not possible for multibranch projects where the groovy script comes from the scm. For more information see https://issues.jenkins-ci.org/browse/JENKINS-28178
I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.
Example:
myvar1 = userInput['param1']
myvar2 = userInput['param2']
to:
myvar = userInput
To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):
import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"
evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)
in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.
To get the version of a maven project, I usually use mvn binary in the sh block as follows. No need for admin permissions.
stage("Compile") {
steps {
sh """
mvn help:evaluate -Dexpression=project.version -q -DforceStdout > version.txt
"""
}
}
Following #JavaTechnical's answer herein a Maven project's version can be assigend to a variable:
stage("getPomProjectVersion") {
steps {
...
def pomProjectVersion = sh script: 'mvn help:evaluate -Dexpression=project.version -q -DforceStdout', returnStdout: true
...
}
}
The issue I had was that the Groovy object didn't have the function I was attempting to call. To my understanding if Groovy can't find the function then Groovy starts to do introspection on the object looking for for the undefined object, which caused this error.
So check to make sure that the function you are trying to call really exists.
Unrelated to OP's issue; But this Stack Overflow Question pops up on top of search.
I was getting this error when I tried to declare a variable named owner (re-declare apparently) in my pipeline script. Changed it to repoOwner and the script worked as expected.

Resources