【问题标题】:Custom Groovy function with arguments doesn't work in Jenkins pipeline带有参数的自定义 Groovy 函数在 Jenkins 管道中不起作用
【发布时间】:2021-07-27 14:47:26
【问题描述】:

我正在使用一个函数在 Jenkins 管道中设置环境变量。我注意到,如果我声明没有参数的函数,它可以工作,但如果我声明接受 1 个字符串参数的函数,Jenkins 在运行我的管道时会抛出错误 No such DSL method 'get_metadata' found among steps

def get_metadata(String type) {
    switch(type) {
      case "env":
        return "environment name";
        break;
      case "domain":
        return "domain name";
        break;
      case "cloud":
        return "cloud name";
        break;
      default:
        return "none";
        break;
    }
}

pipeline {
  environment {
    PROJECT=get_metadata()
    CLOUD=get_metadata(type: "cloud")
    DOMAIN=get_metadata(type: "domain")
    ENVIRONMENT=get_metadata(type: "env")
  }
}

当我将其称为 get_metadata() 时,没有参数的函数有效

def get_metadata() {
<...>
}

Jenkins 版本是 2.289.2。

【问题讨论】:

  • 您的get_metadata 没有为type 定义默认值,因此对PROJECT=get_metadata() 的调用会引发错误,因为如果没有type 参数,您将无法按原样使用它。
  • @NoamHelmer 这是正确答案,因此您可能希望将评论转换为答案。

标签: jenkins jenkins-pipeline jenkins-groovy jenkins-job-dsl


【解决方案1】:

您的get_metadata 没有定义类型的默认值,因此对PROJECT=get_metadata() 的调用会引发错误,因为如果不传递type 参数,您将无法按原样使用它。

要解决这个问题,您只需在函数中添加一个默认值:

def get_metadata(String type = '') {
   switch(type) {
     case "env":
        return "environment name";
     case "domain":
        return "domain name";
     case "cloud":
        return "cloud name";
     default:
        return "none";
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2017-12-24
    • 2019-05-09
    • 2019-02-04
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多