Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a Groovy variable in Jenkins?

I have the following code within a Jenkins pipeline:

stage ('Question') {     try {         timeout(time: 1, unit: 'MINUTES') {             userInput = input message: 'Choose server to publish to:', ok: '', parameters: [                 [$class: 'hudson.model.ChoiceParameterDefinition', choices: 'pc-ensureint\nother-server', description: 'Choose server to publish to:', name: 'server']         ]        }     } catch (err) {         userInput = [server: 'pc-ensureint'] // if an error is caught set this value     } }  node () {     println ${server} } 

I'm trying to troubleshoot a problem with the server variable which is set in the ChoiceParameterDefinition.

When I run the build, I get the following error:

java.lang.NoSuchMethodError: No such DSL method '$' found among steps [AddInteractivePromotion, ArtifactoryGradleBuild, ArtifactoryMavenBuild, ConanAddRemote, ConanAddUser, InitConanClient, MavenDescriptorStep, RunConanCommand, ansiblePlaybook, archive, artifactoryDownload, artifactoryPromoteBuild, artifactoryUpload, bat, build, catchError, checkout, collectEnv, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, dockerPullStep, dockerPushStep, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, getArtifactoryServer, getContext, getDatabaseConnection, git, input, isUnix, library, libraryResource, load, mail, milestone, newArtifactoryServer, newBuildInfo, newGradleBuild, newMavenBuild, node, parallel, properties, publishBuildInfo, pwd, readFile, readTrusted, resolveScm, retry, script, sh, sleep, sql, stage, stash, step, svn, timeout, timestamps, tool, unarchive, unstash, validateDeclarativePipeline, waitForQualityGate, waitUntil, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, wrap, writeFile, ws, xrayScanBuild] or symbols [all, allOf, always, ant, antFromApache, antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, batchFile, booleanParam, branch, buildButton, buildDiscarder, caseInsensitive, caseSensitive, choice, choiceParam, cleanWs, clock, cloud, command, configFile, configFileProvider, cron, crumb, defaultView, demand, disableConcurrentBuilds, docker, dockerfile, downloadSettings, downstream, dumb, envVars, environment, expression, file, fileParam, filePath, fingerprint, frameOptions, freeStyle, freeStyleJob, git, github, githubPush, gradle, hyperlink, hyperlinkToModels, installSource, jdk, jdkInstaller, jgit, jgitapache, jnlp, jobName, junit, label, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logRotator, loggedInUsersCanDoAnything, masterBuild, maven, maven3Mojos, mavenErrors, mavenMojos, mavenWarnings, modernSCM, msbuild, msbuildError, msbuildWarning, myView, node, nodeProperties, nonStoredPasswordParam, none, not, overrideIndexTriggers, paneStatus, parameters, password, pattern, pipeline-model, pipelineTriggers, plainText, plugin, pollSCM, projectNamingStrategy, proxy, queueItemAuthenticator, quietPeriod, remotingCLI, run, runParam, schedule, scmRetryCount, search, security, shell, skipDefaultCheckout, skipStagesAfterUnstable, slave, stackTrace, standard, status, string, stringParam, swapSpace, text, textParam, tmpSpace, toolLocation, unsecured, upstream, usernameColonPassword, usernamePassword, viewsTabBar, weather, withSonarQubeEnv, zfs, zip] or globals [Artifactory, currentBuild, docker, env, params, pipeline, scm]     at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:149)     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.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)     at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)     at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:123)     at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:123)     at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:16)     at WorkflowScript.run(WorkflowScript:16)     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.GeneratedMethodAccessor637.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.ClosureBlock.eval(ClosureBlock.java:46)     at com.cloudbees.groovy.cps.Next.step(Next.java:74)     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:165)     at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:330)     at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:82)     at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:242)     at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:230)     at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)     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 

As far as I know, server is a groovy variable and thus I'm supposed to be able to access it using ${ }.

So I've tried:

echo ${server} print ${server} println ${server} println "${server}" 

But no matter what I try I keep getting this error.

Any idea what I'm doing wrong?

like image 756
Itai Ganot Avatar asked May 09 '17 09:05

Itai Ganot


People also ask

How do I print values in Groovy?

You can print the current value of a variable with the println function.

Can we use echo in Groovy?

Note that echo does not work in Groovy itself - only in Jenkins. println works in both.

How do I get parameters in Jenkins pipeline?

You can generate the parameter pipeline code block easily using the Jenkins pipeline generator. You will find the Pipeline syntax generator link under all the pipeline jobs, as shown in the image below. Navigate to the pipeline generator in Jenkins and under steps, search for properties, as shown below.


2 Answers

The following code worked for me:

echo userInput 
like image 150
yorammi Avatar answered Oct 09 '22 18:10

yorammi


You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

like image 21
Jon S Avatar answered Oct 09 '22 18:10

Jon S