【问题标题】:How to refer to the parameters in groovy pipeline script?如何引用groovy管道脚本中的参数?
【发布时间】:2019-12-18 22:08:54
【问题描述】:

我将其合并为 vars/gitCheckout.goovy 将其作为库添加到 jenkins 中

def call(String branch = '*/master') {
  checkout([$class: 'GitSCM',
      branches: [[name: ${branch}]],
      doGenerateSubmoduleConfigurations: false,
      extensions: [[$class: 'SubmoduleOption',
                    disableSubmodules: false,
                    parentCredentials: false,
                    recursiveSubmodules: true,
                    reference: '',
                    trackingSubmodules: false]],
      submoduleCfg: [],
      userRemoteConfigs: [[url: 'https://my-server.com/some/project.git']]])
}

从 jenkins Pipeline Script 调用这个方法如下:

@Library('jenkins-library@master') _

pipeline {
  agent { label 'my-server' }
  stages {
    stage('Git Checkout') {
        steps {
        gitCheckout()
        }
  }
  }
}

这会失败并出现错误java.lang.NoSuchMethodError: No such DSL method '$' found among steps [ArtifactoryGradleBuild, MavenDescriptorStep, ....

我尝试了 $branch、params.branch,但它不起作用,如果我不使用参数并硬编码分支名称,代码会起作用。另外,每当我对这个 .groovy 脚本进行任何更新时,我是否应该通过将它合并并作为 jenkins 作业运行来测试它?在合并 groovy 脚本之前还有其他方法可以测试吗?

【问题讨论】:

    标签: jenkins-pipeline jenkins-groovy


    【解决方案1】:

    将第 3 行中的 ${branch} 替换为 branch。例如,当您使用 $ 和变量名时在 Groovy 字符串中插入变量:

    def value = "current branch is: ${branch}" // produces: current branch is */master
    

    如果你忘记在字符串插值中使用$,什么都不会发生:

    def value = "current branch is: branch" // produces: current branch is branch
    

    【讨论】:

    • 谢谢,当我不传入任何参数时它可以工作,但是当我尝试以gitCheckout('some-sha') 调用该函数时,它失败并出现错误No signature of method: gitCheckout.call() is applicable for argument types: (java.lang.String) values,我尝试通过gitCheckout('*/master')进行测试,仍然是同样的错误。
    • 检查您是否正确命名文件。我刚刚注意到您在问题中提到了vars/gitCheckout.goovy。也许这只是文本中的一个错字。该错误表明无法找到 gitCheckout 自定义变量 - 这可能是由不正确的文件名引起的。您显示的调用函数的签名看起来不错。
    猜你喜欢
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    相关资源
    最近更新 更多