How to use RTC plugin from jenkins pipeline groovy script? - jenkins

I know I can use scm polling via a Jenkins RTC plugin, I'm just wondering if there's an example of how to do this via the groovy script for the pipeline plugin?
For example:
node{
stage 'Checkout'
git url: 'https://github.com/whatever/myrepo.git'
...
}
Something like above but instead of git, you use rtc toolkit with prod url and specify a stream or a workspace... Cannot find an example anywhere and not sure how to go about implementing it via api (or if that's even possible?)

Actually the snippet generator is a bit misleading in that it does not generate all that you need. For example, based on what was generated I used this in the pipeline:
node {
teamconcert([buildDefinition: 'TestStream', value: 'buildDefinition'])
}
If you use it as is you will get this exception:
RTC : checkout...
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NullPointerException
at com.ibm.team.build.internal.hjplugin.RTCScm.checkout(RTCScm.java:1948)
atorg.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:109)
at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:83)
at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:73)
at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:52)
at hudson.security.ACL.impersonate(ACL.java:221)
at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:49)
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 syntax that you require is this:
node {
teamconcert([
buildType: [
buildDefinition: 'TestStream',
value: 'buildDefinition'
]
])
}
Team concert expects things to be wrapped in a 'buildType'. I found this in a forum answer on jazz.net, have not seen it documented anywhere else.

There is a snippet code generator right there in the pipeline plugin, took me a while to find it, but it will generate the groovy code for any Jenkins task... Rtc is listed under teamconcert: Team Concert, just scroll down to the bottom and tick the Snippet Generator checkbox!

Related

Issue in Jenkins integration with GitHub and Ionic project

I am trying to integrate ionic application with Jenkins and i am using GitHub as a repository. When i run the Multibranch pipeline job manually, the Jenkin is displaying below error.
Does anyone know what can be possible issue ? I am trying to learn how CI/CD works with this demo experiment.
I am referring this Youtube video : https://www.youtube.com/watch?v=q5voVJb3rHI&t=605s
Started by user admin
13:42:45 Connecting to https://api.github.com using PrashobThekkyal/*****
Obtained Jenkinsfile from a85fffb01a96c5c5d550326873047c6071557aff
Running in Durability level: MAX_SURVIVABILITY
GitHub has been notified of this commit’s build result
java.lang.IllegalArgumentException: Unsupported class file major version 57
at org.kohsuke.asm6.ClassReader.<init>(ClassReader.java:176)
at org.kohsuke.asm6.ClassReader.<init>(ClassReader.java:158)
at org.kohsuke.asm6.ClassReader.<init>(ClassReader.java:146)
at org.jenkinsci.bytecode.helper.ClassLoadingReferenceTypeHierachyReader.reader(ClassLoadingReferenceTypeHierachyReader.java:64)
at org.jenkinsci.bytecode.helper.TypeHierarchyReader.hierarchyOf(TypeHierarchyReader.java:176)
at org.jenkinsci.bytecode.helper.ClassLoadingReferenceTypeHierachyReader.hierarchyOf(ClassLoadingReferenceTypeHierachyReader.java:39)
at org.jenkinsci.bytecode.helper.TypeHierarchyReader$TypeHierarchy.isAssignableFrom(TypeHierarchyReader.java:321)
at org.jenkinsci.bytecode.helper.TypeHierarchyReader$TypeHierarchy.isAssignableFromAnyInterfaceImplementedBy(TypeHierarchyReader.java:329)
at org.jenkinsci.bytecode.helper.TypeHierarchyReader$TypeHierarchy.isAssignableFrom(TypeHierarchyReader.java:311)
at org.jenkinsci.bytecode.helper.TypeHierarchyReader.isAssignableFrom(TypeHierarchyReader.java:124)
at org.jenkinsci.bytecode.helper.ClassLoadingReferenceTypeHierachyReader.isAssignableFrom(ClassLoadingReferenceTypeHierachyReader.java:39)
at org.jenkinsci.bytecode.helper.TypeHierarchyReader.getCommonSuperClass(TypeHierarchyReader.java:131)
at org.jenkinsci.bytecode.helper.ClassLoadingReferenceTypeHierachyReader.getCommonSuperClass(ClassLoadingReferenceTypeHierachyReader.java:39)
at org.jenkinsci.bytecode.NonClassLoadingClassWriter.getCommonSuperClass(NonClassLoadingClassWriter.java:72)
at org.kohsuke.asm6.SymbolTable.addMergedType(SymbolTable.java:1209)
at org.kohsuke.asm6.Frame.merge(Frame.java:1293)
at org.kohsuke.asm6.Frame.merge(Frame.java:1238)
at org.kohsuke.asm6.MethodWriter.computeAllFrames(MethodWriter.java:1604)
at org.kohsuke.asm6.MethodWriter.visitMaxs(MethodWriter.java:1540)
at org.kohsuke.asm6.tree.MethodNode.accept(MethodNode.java:807)
at org.kohsuke.asm6.commons.JSRInlinerAdapter.visitEnd(JSRInlinerAdapter.java:150)
at org.jenkinsci.bytecode.Transformer$1$1.visitEnd(Transformer.java:109)
at org.kohsuke.asm6.MethodVisitor.visitEnd(MethodVisitor.java:783)
at org.kohsuke.asm6.ClassReader.readMethod(ClassReader.java:1278)
at org.kohsuke.asm6.ClassReader.accept(ClassReader.java:679)
at org.kohsuke.asm6.ClassReader.accept(ClassReader.java:391)
at org.jenkinsci.bytecode.Transformer.transform(Transformer.java:115)
at hudson.ClassicPluginStrategy$AntClassLoader2.defineClassFromData(ClassicPluginStrategy.java:706)
at jenkins.util.AntClassLoader.getClassFromStream(AntClassLoader.java:1310)
at jenkins.util.AntClassLoader.findClassInComponents(AntClassLoader.java:1363)
at jenkins.util.AntClassLoader.findClass(AntClassLoader.java:1326)
at jenkins.util.AntClassLoader.loadClass(AntClassLoader.java:1079)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at org.jenkinsci.plugins.workflow.cps.CpsScript.<init>(CpsScript.java:69)
at WorkflowScript.<init>(WorkflowScript)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166)
at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404)
at java.base/java.lang.Class.newInstance(Class.java:591)
at org.codehaus.groovy.runtime.InvokerHelper.createScript(InvokerHelper.java:434)
Caused: groovy.lang.GroovyRuntimeException: Failed to create Script instance for class: class WorkflowScript. Reason
at org.codehaus.groovy.runtime.InvokerHelper.createScript(InvokerHelper.java:466)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:327)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
Jenkinsfile
pipeline {
agent any
stages {
stage ('Build') {
steps {
echo "Building Multibranch Pipeline"
}
}
stage ('Testing') {
steps {
echo "Testing Multibranch Pipeline"
}
}
stage ('Deployment') {
steps {
echo "False Deploying Multibranch Pipeline"
}
}
}
}
Jenkins Job configuration:
After days of analysis finally I have found the solution. I have did a very basic mistake of not reading version requirement to run Jenkins.
Java requirement to run Jenkins job
As mentioned in above URL, under the section 'Running Jenkins', they have clearly mentioned the support versions of java to run Jenkins job. So I checked java version and it was running on Java 13-a, yes that was stupid, because the Jenkins job will only run with java version 8 and 11.
So degrade your java version to 8 or 11 and it will work smoothly.
Proof
I thought to delete my stupid question, but later I thought to keep it, if in case it could help somebody. Kindly please don't give any kind of (+ve or -vew) points to this post, as it doesn't make any sense.

Unspecified Jenkinsfile Null Pointer Error in Workflow Steps

I encountered the following error in a Jenkinsfile pipeline I was building:
java.lang.NullPointerException
at org.jenkinsci.plugins.workflow.steps.CoreStep$Execution.run(CoreStep.java:80)
at org.jenkinsci.plugins.workflow.steps.CoreStep$Execution.run(CoreStep.java:67)
at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
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
The issue here, primarily, is that I'm not sure exactly what is going on. Since all it's mentioning is a null pointer error, I can't exactly be sure, and I can't find anything more specific.
Here's my Jenkinsfile:
#!groovy
node {
withEnv(["WORKSPACE=${pwd()}"]) { //Setting Workspace to the current directory
stage('Clone repository...') {
checkout scm //Let checkout automagically handle pulling in all the names we need and whatnot
}
stage('Building WAR...') {
step(withMaven(
// Maven installation declared in the Jenkins "Global Tool Configuration"
maven: 'Maven 3.6.0') {
// Run the maven build
sh 'mvn clean install' //Same as running on local
sh 'mv ${WORKSPACE}/target/QUserService.war ${WORKSPACE}/target/QUserService_War-QUserService-${BRANCH_NAME}-${BUILD_NUMBER}.war'
//For above line, 'mv' is the Linux command to rename/move files, which is needed for the UCD script
}
// withMaven will discover the generated Maven artifacts, JUnit Surefire & FailSafe & FindBugs reports...
)
}
}
}
So - first, you don't need to define WORKSPACE. It is defined for you by Jenkins. You can convince yourself of this by running sh 'set' on a linux agent.
Next, you don't need to check out the project. It will already be there (assuming you're using a pipeline project).
Next, you don't need to put the withMaven inside of a step call. In a scripted pipeline, the stuff in a stage is groovy script. Step isn't required.
node {
stage('Building WAR...') {
withMaven(
maven: 'Maven 3.5.0') {
// Run the maven build
sh 'mvn clean install' //Same as running on local
}
}
I took out the move step and comment just to make it clearer.
I didn't get a null pointer error. See if removeing the step call and removing the step call make the NPE go away. If not, I'd suggest attaching the console output to attempt to see where this happens.

Printing code coverage status on pull request for Bitbucket stash based repository using JenkinsFile

I currently have a private Bitbucket stash repository e.g. https://xyzgit.company.com/stash/scm/proj1/subproj2.
This is a gradle based project which uses JenkinsFile to manage different stages for Jenkins Job (including setup, build, publish etc). Whenever a new change is committed to a branch, it automatically triggers a build or provide an option to trigger a build. To analyse code coverage, we use Jcoco Plugin which analyzes all subfolders to get the coverage.
My current requirement is to print code coverage status on the pull request after the build is successful over jenkins using JenkinsFile.
I came across a plugin i.e. Bit Bucket Code Coverage Plugin but I did not find any such plugin available to be installed in my Jenkins Environment. I tried to do it manually but it redirects me to plugin available for Github.
I anyway installed that and tried what is suggested in the document i.e. adding these two lines in my Jenkins File :
step([$class: 'MasterCoverageAction', scmVars: [GIT_URL: "https://xyzgit.company.com/stash/scm/proj1/subproj2"]])
step([$class: 'CompareCoverageAction', scmVars: [GIT_URL: "https://xyzgit.company.com/stash/scm/proj1/subproj2"]])
It did not work. I got the following Error :
[GitHub PR Status] Attempt to discover PR for null # null
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withCredentials
[Pipeline] }
[Pipeline] // wrap
[Pipeline] }
[Pipeline] // wrap
[Pipeline] }
[Pipeline] // timestamps
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.io.FileNotFoundException: https://api.github.com/repos/stash/scm
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0
(HttpURLConnection.java:1872) at sun.net.www.protocol.http.
HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.
getResponseCode(HttpsURLConnectionImpl.java:338)
at org.kohsuke.github.Requester.parse(Requester.java:602)
Caused: java.io.FileNotFoundException:
https://api.github.com/repos/stash/scm
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.
newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.
newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.
run(HttpURLConnection.java:1926)
at sun.net.www.protocol.http.HttpURLConnection$10.
run(HttpURLConnection.java:1921)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.
getChainedException(HttpURLConnection.java:1920)
at sun.net.www.protocol.http.HttpURLConnection.
getInputStream0(HttpURLConnection.java:1490)
at sun.net.www.protocol.http.HttpURLConnection.
getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.
getInputStream(HttpsURLConnectionImpl.java:254)
at org.kohsuke.github.Requester.parse(Requester.java:612)
at org.kohsuke.github.Requester.parse(Requester.java:594)
at org.kohsuke.github.Requester._to(Requester.java:272)
Caused: org.kohsuke.github.GHFileNotFoundException: {"message":"Not
Found","documentation_url":"https://developer.github.com/v3"}
at org.kohsuke.github.Requester.handleApiError(Requester.java:686)
at org.kohsuke.github.Requester._to(Requester.java:293)
at org.kohsuke.github.Requester.to(Requester.java:234)
at org.kohsuke.github.GitHub.getRepository(GitHub.java:443)
at com.github.terma.jenkins.githubprcoveragestatus.
GitHubPullRequestRepository.getGitHubRepository
(GitHubPullRequestRepository.java:57)
Caused: java.io.IOException: Could not retrieve GitHub repository named
stash/scm (Do you have properly set 'GitHub project' field in job
configuration?) at com.github.terma.jenkins.githubprcoveragestatus.
GitHubPullRequestRepository.getGitHubRepository
(GitHubPullRequestRepository.java:59) at
com.github.terma.jenkins.githubprcoveragestatus.
GitHubPullRequestRepository.getPullRequestFor
(GitHubPullRequestRepository.java:32)
at com.github.terma.jenkins.githubprcoveragestatus.
PrIdAndUrlUtils.getMultiBranch(PrIdAndUrlUtils.java:63)
at com.github.terma.jenkins.githubprcoveragestatus.
PrIdAndUrlUtils.getPrId(PrIdAndUrlUtils.java:72)
at com.github.terma.jenkins.githubprcoveragestatus.
CompareCoverageAction.perform(CompareCoverageAction.java:93)
at org.jenkinsci.plugins.workflow.steps.
CoreStep$Execution.run(CoreStep.java:80)
at org.jenkinsci.plugins.workflow.steps.
CoreStep$Execution.run(CoreStep.java:67)
at org.jenkinsci.plugins.workflow.steps.
SynchronousNonBlockingStepExecution$1$1.
call(SynchronousNonBlockingStepExecution.java:49)
at hudson.security.ACL.impersonate(ACL.java:260)
at org.jenkinsci.plugins.workflow.steps.
SynchronousNonBlockingStepExecution$1.
run(SynchronousNonBlockingStepExecution.java:46)
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
Can anybody help me if any additional setting is there? or How to inject env CHANGE_URL and CHANGE_ID in JenkinsFile ?
Take a look at Code Coverage Plugin for Bitbucket Server. In it's repo you could find maven-based client which supports JACOCO and could be easily called from gradle.

Jenkins Pipeline conditional stage succeeds but Jenkins shows build as failed

Jenkins version = 2.19
Jenkins Multibranch Pipeline plugin version = 2.92
I have a Jenkinsfile with a few conditional stages based on the branch.
Here is a modified for the sake of brevity version of my Jenkinsfile:
node {
stage('Checkout') {
checkout scm
}
stage('Clean Verify') {
sh 'mvn clean verify'
}
if (env.BRANCH_NAME == "develop") {
stage('Docker') {
sh 'mvn docker:build -DpushImage'
}
}
}
I am using the multibranch pipeline plugin.
It successfully detects and builds all my branches.
The problem I have is that all builds report as failed even though if i hover each stage it reports 'Success'.
I have attached an image showing a feature branch where the two stages i wanted to run have run and completed with success but you can see the build has actually reported as failed.
I get the exact same outcome for develop branch as well - it executes the Docker stage successfully but the build reports failed.
My expectation is that each branch will report success as the stages that ran for that branch all passed.
EDIT 1
Here's the end of the build log (i'm hoping this is sufficient as i didn't want to pick out all the private info but let me know if required)
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 30.459 s
[INFO] Finished at: 2017-02-21T15:13:02+11:00
[INFO] Final Memory: 84M/769M
[INFO] ------------------------------------------------------------------------
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] sh
Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
[Pipeline] End of Pipeline
org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing
at org.jenkinsci.plugins.workflow.steps.StepDescriptor.checkContextAvailability(StepDescriptor.java:253)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:179)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:126)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:108)
at groovy.lang.GroovyObject$invokeMethod.call(Unknown Source)
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:151)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:21)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:115)
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:16)
at WorkflowScript.run(WorkflowScript:93)
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.GeneratedMethodAccessor501.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: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:163)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:328)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:80)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:240)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:228)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:63)
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
So after looking more closely at the log file it helped me to track down the problem.
It's worth noting that clicking on the build stage to view the logs is what threw me - this is what I had been doing. When I actually went to the full console log output i saw the error about:
Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
Underneath the node {} section that I had I had a statement for deploys:
def branch = readFile('branch').trim()
if (branch == master) {
...
}
The problem was that the readFile statement was defined outside of a node.
The answer was to put the readFile statement within a node {} section.
I know this is old, but I ran into a similar issue with a declarative pipeline and landed here. As it turns out, I was trying to use a sh to set an environment variable within the pipeline block, but my main agent was none, i.e.:
pipeline {
agent none
environment {
VERSION = sh(returnStdout: true, script: 'git describe --tags')
}
}
That resulted in the same error Required context class hudson.FilePath is missing. Moving it to a stage with an agent worked as expected.
my solution for the error Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
is:
#!/usr/bin/env groovy
import hudson.model.*
node('master') {
sh("your shell script")
}
In my case, it suddenly stopped working, with the error:
Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
The reason was that the node was simply down. Had to restart it and relaunch its agent (it was slave).
The sh command is not closed with a quote in the end.
This error can happen if your branch gets deleted and will show the below error:
Caused by: org.codehaus.groovy.runtime.InvokerInvocationException:
org.jenkinsci.plugins.workflow.steps.MissingContextVariableException:
Required context class hudson.FilePath is missing 14:25:07 Perhaps
you forgot to surround the code with a step that provides this, such
as: node
and THEN at the end it will also say:
ERROR: Couldn't find any revision to build. Verify the repository and
branch configuration for this job.
In our case we had sometimes set a job to use a branch that was still in a PR and once the PR was merged the branch was auto-deleted (e.g. https://stackoverflow.com/a/57328204/292408).
Restore the branch in the job if this is your case and it should work again. If you are seeing this error inconsistently then this might be your issue.
I had this error:
Error when executing always post condition: org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
It was caused by ambiguous interpolation:
environment {
FILE = "some-$BRANCH.yml"
}
The correct expression in this case would be:
"some-${BRANCH}.yml"

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