如何在groovy管道脚本中引用参数?

时间:2019-12-18 22:08:54

标签: jenkins-pipeline jenkins-groovy

我将其合并为vars/gitCheckout.goovy,并将其作为库添加到詹金斯中

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脚本中按以下方式调用此方法:

@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脚本之前还有其他测试方法吗?

1 个答案:

答案 0 :(得分:1)

仅将${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