简体   繁体   中英

Groovy parameter to shell script

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:

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:

在此处输入图像描述

Reference: Jenkins - Passing parameter to groovy function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM