PandaSITT
PandaSITT

Reputation: 67

Access Jenkins Parameter in Groovy

How can I access the value of a parameter in Groovy? This seems like a trivial problem, but it has caused me to many hours of pain.

dslFactory.job(name) {

            parameters {
                activeChoiceParam('ENTERPRISESERVER') {
                    description('')
                    choiceType('SINGLE_SELECT')
                    groovyScript {
                        script("""[
                            "vws-10-persmft",
                            "vws-10-persmft2",
                            "vws-10-persmft3",
                            // "vws-10-persmfe",
                            // "vws-10-persmfe2",
                            "vts-10-perse9",
                            //"vts-10-perse8",
                            //"vts-10-perse7",
                            "vws-10-perskmt5"
                        ]""")
                    }
                }
            }

            steps {
                def targetServer = '${ENTERPRISESERVER}'
                powerShell """
                    Write-Output 'Target Server: $targetServer'
                    Invoke-Command -ComputerName '$targetServer' -ScriptBlock {
                        Restart-Service -Name 'SEEShutdown';
                        Restart-Service -Name 'SEEMonitor';
                    };
                """
            }
        }

When I run that code, I'm getting the following error:

+ ...             Invoke-Command -ComputerName '${ENTERPRISESERVER}' -Scrip ...

So for some reason, Groovy doesn't resolve ${ENTERPRISESERVER}. I have tried using $ENTERPRISESERVER, and it won't compile:

de.akdb.pers.ci.JobScriptsSpec > test script bootstrap.groovy FAILED
    org.spockframework.runtime.UnallowedExceptionThrownError at JobScriptsSpec.groovy:24
        Caused by: javaposse.jobdsl.dsl.DslScriptException at JobScriptsSpec.groovy:21
            Caused by: groovy.lang.MissingPropertyException at JobScriptsSpec.groovy:21

What am I doing wrong?

I also tried the solutions from the following questions:

Jenkins Job DSL: Using parameters in groovyScript in job step

How to access a specific Jenkins job parameter from within a JobDSL?

How to retrieve Jenkins build parameters using the Groovy API?

Upvotes: 0

Views: 258

Answers (2)

Andy Jiang
Andy Jiang

Reputation: 38

In my understanding, the ENTERPRISESERVER is defined for the job your are gonna create, it isn't valid in the dsl code of creating that job.
Which means ENTERPRISESERVER is directly visible and usable in the PowerShell script.
I never used PowerShell, but in BASH it can be accessed thru "$ENTERPRISESERVER".
A shell script inside dsl code should escape param/var dereference with "\$ENTERPRISESERVER".
Have a try!

Upvotes: 1

ycr
ycr

Reputation: 14574

Try one of the following.

def targetServer = "${ENTERPRISESERVER}"
def targetServer = params.ENTERPRISESERVER

Upvotes: 0

Related Questions