6

How can we pass parameters in Groovy script in Jenkins pipeline?

I have written xyz.groovy, it loads and executes fine but i would like to pass parameters in it instead of duplication of jobs. I tried passing load '../xyz.groovy' param1 param2 but no luck.

Pipeline script:

node {
    load '../xyz.groovy'
}()

xyz.groovy

import hudson.model.*
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import java.net.URL

echo "\nParameters.."
echo param1
echo param2
halfer
  • 19,824
  • 17
  • 99
  • 186
Jitesh Sojitra
  • 3,655
  • 7
  • 27
  • 46

2 Answers2

2

Can't you do something similar to this instead: How do you load a groovy file and execute it

You create methods in your groovy that you call with the parameters?

node {
    def script = load '../xyz.groovy'
    script.method(param1, param2)
}
Community
  • 1
  • 1
MaTePe
  • 936
  • 1
  • 6
  • 11
1

This can be done simply by using the ${jenkins_param} syntax

e.g

  • define a string param in the Jenkins build job called RELEASE_VERSION = "1.0"
  • reference this as ${RELEASE_VERSION} in the groovy script

This will resolve as "1.0" when the script is running

Ivan Aracki
  • 4,861
  • 11
  • 59
  • 73
danlaffan
  • 11
  • 1
  • This works because you can reference `params.xyz` with `env.xyz`. You can't access `params` outside of the pipeline (unless you pass in the params object), but you can access `env` anywhere. And, in the above example, `${RELEASE_VERSION}` really means `${env.RELEASE_VERSION}`. I haven't played with non-string params as env vars; i would assume they are transformed to strings. – Max Cascone Oct 28 '20 at 19:31