Jenkins Pipeline errors out accepting multiple values from a groovy method

Viewed 2477

I'm trying to accept multiple values from a groovy method into a Jenkins pipeline and keep hitting Pipeline Workflow errors, any pointers as to what I'm doing wrong here is greatly appreciated.

(env.var1, env.var2, env.var3) = my_func()

def my_func(){
  def a =10
  def b =10
  def c =10
  return [a, b, c]
}

I get following error:

expecting ')', found ','  @(env.var1, env.var2, env.var3) = my_func()
1 Answers

You are using Groovy's multiple assignment feature incorrectly. It works when you assign a collection of values to a list of new variables. You can't use this type of assignment to assign values to an existing object. Your code also fails when executed in plain Groovy:

def env = [foo: 'bar']

(env.var1, env.var2, env.var3) = my_func()

println env

def my_func(){
  def a =10
  def b =10
  def c =10
  return [a,b,c]
}

Output:

1 compilation error:

expecting ')', found ',' at line: 3, column: 14

In Jenkins environment, env variable is represented not by a map, but by EnvActionImpl object which means it does not even support plus() or putAll() methods. It only overrides getProperty() and setProperty() methods, so you can access properties with env.name dot notation.

Solution

The simplest solution to your problem is to use multiple assignment correctly and then set env variables from variables. Consider following example:

node {
    stage("A") {
        def (var1, var2, var3) = my_func()
        env.var1 = var1
        env.var2 = var2
        env.var3 = var3
    }

    stage("B") {
        println env.var1
    }
}

def my_func() {
  def a = 10
  def b = 10
  def c = 10
  return [a, b, c]
}

Keep in mind that var1, var2 and var3 variables cannot already exist in current scope, otherwise compiler will throw an exception.

Related