简体   繁体   English

Groovy 参数到 shell 脚本

[英]Groovy parameter to shell script

I've been trying to separate my code into two different files: callTheFunction.groovy and theFunction.groovy .我一直在尝试将我的代码分成两个不同的文件: callTheFunction.groovytheFunction.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. callTheFunction.groovy调用定义在Function.groovy中的theFunction.groovy ,将随机值作为参数传入。
  • theFunction is a shell script - inside groovy function - which is supposed to use the parameters passed from callTheFunction . theFunction是一个 shell 脚本 - 在 groovy function 内 - 它应该使用从callTheFunction传递的参数。

PROBLEM:问题:
The shell script does not recognize/understand the arguments, the variables are empty, no value. shell 脚本无法识别/理解 arguments,变量为空,没有值。

theFunction.groovy theFunction.groovy

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

callTheFunction.groovy调用TheFunction.groovy

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

OUTPUT FROM PIPELINE: OUTPUT 来自管道:

MY values  and

I am aware that there are similar issues out there:我知道那里有类似的问题:

UPDATES更新

You can use environment variable without having environment {}您可以在没有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:对 shell 脚本使用三重单引号进行循环并向其中添加 grrovy 变量:

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: OUTPUT:

在此处输入图像描述

Reference: Jenkins - Passing parameter to groovy function参考: Jenkins - 将参数传递给 groovy function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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