wake-up-neo.com

Wie drucke ich eine groovige Variable?

Ich habe den folgenden Code in einer 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}
}

Ich versuche, ein Problem mit der "Server" -Variablen zu beheben, die in der "ChoiceParameterDefinition" festgelegt ist.

Beim Ausführen des Builds wird folgende Fehlermeldung angezeigt:

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

Soweit ich weiß, ist "server" eine groovige Variable und daher soll ich in der Lage sein, mit $ {} darauf zuzugreifen.

Also habe ich versucht:

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

Aber egal was ich versuche, ich bekomme immer wieder diesen Fehler.

Irgendeine Idee, was ich falsch mache?

14
Itai Ganot

Der folgende Code hat bei mir funktioniert:

echo userInput
21
yorammi

Sie sollten nicht ${varName} Verwenden, wenn Sie sich außerhalb von Strings befinden, sondern nur varName. Innerhalb von Strings verwenden Sie es wie folgt; echo "this is a string ${someVariable}";. In der Tat können Sie einen allgemeinen Java Ausdruck innerhalb von ${...}; echo "this is a string ${func(arg1, arg2)} platzieren.

8
Jon S