3

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:

user1098490
  • 478
  • 1
  • 4
  • 16
  • you have to read also about strings in groovy and what's the difference between single-quoted string and double-quoted string. https://groovy-lang.org/syntax.html#all-strings – daggett Aug 07 '20 at 13:02
  • What I should've added is: If I have the shell script in the same file as the variables it works. So if I define global variables `def var1 = "myvalue"` and `def var2 = "myothervalue`, and have the shell script in the same file, it works. – user1098490 Aug 07 '20 at 13:33
  • 2
    just replace quotes: `sh ''' ... '''` with `sh """ ... """` – daggett Aug 07 '20 at 13:57
  • Just got an example: Let's say I use `sh """ ... """`, what do I do if I got a for loop and `sed`, example: `for i in a b c; do sed -i '/^$i/d` myfile` --> This would not work, because when you use **triple-double-quotes** you have to escape the shell variables, meaning my sed would look like this: `sed -i '/^\$i/d myfile`. `sed` is no longer looking for my variable `$i`, but instead the character `$` and `i`. – user1098490 Aug 07 '20 at 14:24
  • use [environment variables](https://www.jenkins.io/doc/pipeline/tour/environment/). or use `''' ... ''' + variable + ''' ... '''` to inject variable values – daggett Aug 08 '20 at 01:34

1 Answers1

0

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

Aditya Nair
  • 514
  • 1
  • 9
  • 18