is it possible to run jenkins job from groovy script?
I know it is possible to run jenkins job from pipeline like this
build job: 'test'
this also doesn't work
build('test')
error for
build job: 'test'
Caught: groovy.lang.MissingMethodException: No signature of method: hudson8298793087824999032.build() is applicable for argument types: (LinkedHashMap) values: [[job:test]]
Possible solutions: find(), find(groovy.lang.Closure), wait(), run(), run(), dump()
groovy.lang.MissingMethodException: No signature of method: hudson8298793087824999032.build() is applicable for argument types: (LinkedHashMap) values: [[job:test]]
Possible solutions: find(), find(groovy.lang.Closure), wait(), run(), run(), dump()
at hudson8298793087824999032.run(hudson8298793087824999032.groovy:32)
Build step 'Execute Groovy script' marked build as failure
After edit Execute system Groovy script and added
def currentBuild = Thread.currentThread().executable
def job = hudson.model.Hudson.instance.getJob("jobname")
println(job)
def params = new StringParameterValue('version', '1.0.0')
println(params)
def params1 = new StringParameterValue('target', "dev")
println(params1)
def paramsAction = new ParametersAction(params, params1)
println(paramsAction)
def cause = new hudson.model.Cause.UpstreamCause(currentBuild)
println(cause)
def causeAction = new hudson.model.CauseAction(cause)
println(causeAction)
println('test')
Hudson.instance.queue.schedule(job, 0, causeAction, paramsAction)
I got error on this line Hudson.instance.queue.schedule(job, 0, causeAction, paramsAction)
java.lang.NullPointerException
at hudson.model.queue.Tasks.getOwnerTaskOf(Tasks.java:60)
at com.cloudbees.hudson.plugins.folder.ItemDeletion.getItemOf(ItemDeletion.java:197)
at com.cloudbees.hudson.plugins.folder.ItemDeletion.shouldSchedule(ItemDeletion.java:174)
at hudson.model.Queue.schedule2(Queue.java:589)
at hudson.model.Queue.schedule2(Queue.java:712)
at hudson.model.Queue.schedule(Queue.java:705)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:192)
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.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:149)
at Script1.run(Script1.groovy:47)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:585)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:623)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:594)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:343)
at hudson.plugins.groovy.SystemGroovy.run(SystemGroovy.java:95)
at hudson.plugins.groovy.SystemGroovy.perform(SystemGroovy.java:59)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
at hudson.model.Build$BuildExecution.build(Build.java:206)
at hudson.model.Build$BuildExecution.doRun(Build.java:163)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
at hudson.model.Run.execute(Run.java:1818)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429)
Build step 'Execute system Groovy script' marked build as failure
For me, I needed the code to run on the master to have quick access to the Jenkins objects and build a job that has the appropriate permissions to send a mail within the information acquired.
I used the build module Execute system Groovy Script to run the script and appended the following code:
// The job you want to run from groovy
def job = hudson.model.Hudson.instance.getJob("SendEmailJob")
// jobsList is a list of jobs of interest formated as HTML
def body = jobsList
def params = []
params += new StringParameterValue('TO', "<team#example.com>")
params += new StringParameterValue('BODY_AS_HTML', body)
params += new StringParameterValue('SUBJECT', "List of jobs of interest")
def paramsAction = new ParametersAction(params)
def cause = new hudson.model.Cause.UpstreamCause(build)
def causeAction = new hudson.model.CauseAction(cause)
hudson.model.Hudson.instance.queue.schedule(job, 0, causeAction, paramsAction)
This is based on question how-do-i-dynamically-trigger-downstream-builds-in-jenkins
Related
I'm coding a library for my Jenkins pipelines. I would like to print different formats for my messages, like [INFO], [WARNING] and so on.
So far I have this:
import org.foo.Output
def call(body) {
def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
def out = new Output()
node("${config.slaveNodeName}") {
try {
stage ('CLONE') {
out.info("SOME VERY USEFUL INFORMATION")
...
And at my org.foo.Output class:
package org.foo
import java.util.logging.Logger
class Output {
private static final Logger LOGGER = Logger.getLogger(Output.class.getName());
def info(msg){
LOGGER.info("${msg}")
echo "[INFO] ${msg}" <-- gives me an exception described below
}
}
I can see the [INFO] SOME VERY USEFUL INFORMATION on my Jenkins log, however, I would like to redirect this message to Jenkins output console.
How can I do that?
Exception:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: org.foog.Output.echo() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [[INFO] SOME VERY USEFUL INFORMATION]
Possible solutions: each(groovy.lang.Closure), info(java.lang.Object), wait(), grep(), any(), find()
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:19)
Valter, try this one. It's working in my scripts, I think it would also work in your scripts.
In groovy script, add this:
node("${config.slaveNodeName}") {
try {
stage ('CLONE') {
out.info(this,"SOME VERY USEFUL INFORMATION")
and change the class groovy script like this:
def info(script,msg){
LOGGER.info("${msg}")
script.echo "[INFO] ${msg}"
}
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
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'}"
I am using the build flow project for combining the two different project test results.Then i am in need to change the build status of the aggregated test results so i am using groovy postbuild to change my build status.In that script if any one of the test fails gets failed in any of the projects then i am trying to change the build status to unstable.For that i am calculating the fail counts from both results using groovy script.But when i am trying this it throws the NULL pointer Exception.
The script i used in the groovy postbuild is
def testResult = manager.build.testResultAction.result
def fail = testResult.failCount
if(fail==NULL)
{ manager.buildSuccess() }
else
{ manager.buildUnstable() }
It throws the exception as
ava.lang.NullPointerException: Cannot get property 'result' on null object
at org.codehaus.groovy.runtime.NullObject.getProperty(NullObject.java:56)
at org.codehaus.groovy.runtime.InvokerHelper.getProperty(InvokerHelper.java:156)
at org.codehaus.groovy.runtime.callsite.NullCallSite.getProperty(NullCallSite.java:44)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at Script1.run(Script1.groovy:1)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:166)
at org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder.perform(GroovyPostbuildRecorder.java:362)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:782)
at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:723)
at hudson.model.Build$BuildExecution.post2(Build.java:185)
at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:668)
at hudson.model.Run.execute(Run.java:1763)
at hudson.model.FreeStyleBuild.run``(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:410)
Activity
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}"
}