Groovy parameter to shell script

Viewed 1444

I've been trying to separate my code into two different files: callTheFunction.groovy and theFunction.groovy.

As you can see from the name of the file:

  • callTheFunction.groovy calls the function defined in theFunction.groovy, passing random values in as parameters.
  • theFunction is a shell script - inside groovy function - which is supposed to use the parameters passed from callTheFunction.

PROBLEM:
The shell script does not recognize/understand the arguments, the variables are empty, no value.

theFunction.groovy

def call(var1, var2) {
  sh '''
    echo "MY values $var1 and $var2"
  '''
}

callTheFunction.groovy

def call {
  pipeline {
    stages {
      stage ('myscript') {
        steps {
          theFunction("Value1", "Value2")
        }
      }
    }
  }
}

OUTPUT FROM PIPELINE:

MY values  and

I am aware that there are similar issues out there:

1 Answers

UPDATES

You can use environment variable without having environment {}

Use environment variables like the ones i have used here (i refactored your code a little bit). Using triple single quotes for shell script for loop and adding grrovy variable to it:

def callfunc() {
  sh '''
  export s="key"
  echo $s
  for i in $VARENV1 
    do
      echo "Looping ... i is set to $i"
    done
    '''
}

pipeline {
    agent { label 'agent_1' }
    stages {
      stage ('Run script') {
        steps {
            script {
                env.VARENV1 = "Peace"
            }
            callfunc()
        }
      }
    }
}

OUTPUT:

enter image description here

Reference: Jenkins - Passing parameter to groovy function

Related