如何参数化 Jenkinsfile 作业

How can I parameterize Jenkinsfile jobs

我有 Jenkins Pipeline 作业,其中作业之间的唯一区别是参数,单个 "name" 值,我什至可以使用多分支作业名称(尽管不是它作为 JOB_NAME 这是 BRANCH 名称,遗憾的是 none envs 在没有解析的情况下看起来很合适)。如果我可以在 Jenkinsfile 之外设置这个,那就太好了,从那时起我可以为所有不同的工作重用同一个 jenkinsfile。

将此添加到您的 Jenkinsfile:

properties([
  parameters([
    string(name: 'myParam', defaultValue: '')
  ])
])

然后,一旦构建有 运行 一次,您将在作业 UI.

上看到 "build with parameters" 按钮

在那里你可以输入你想要的参数值。

在管道脚本中,您可以使用 params.myParam

来引用它

在您的管道作业配置中有一个选项此项目已参数化。如果您愿意,可以写下变量名和默认值。在管道中使用 env.variable_name

访问此变量

基本上你需要创建一个 jenkins shared library example name myCoolLib and have a full declarative pipeline in one file under vars,假设你调用文件 myFancyPipeline.groovy.

想写我的示例,但实际上我看到了 the docs are quite nice,所以我将从那里复制。首先是 myFancyPipeline.groovy

def call(int buildNumber) {
  if (buildNumber % 2 == 0) {
    pipeline {
      agent any
      stages {
        stage('Even Stage') {
          steps {
            echo "The build number is even"
          }
        }
      }
    }
  } else {
    pipeline {
      agent any
      stages {
        stage('Odd Stage') {
          steps {
            echo "The build number is odd"
          }
        }
      }
    }
  }
}

然后是使用它的 Jenkins 文件(现在有 2 行)

@Library('myCoolLib') _
evenOrOdd(currentBuild.getNumber())

很明显这里的参数是int类型的,但是可以是任意数量任意类型的参数。

我使用这种方法并且有一个 groovy 脚本有 3 个参数(2 个字符串和一个 int)并且有 15-20 个 Jenkinsfiles 通过共享库使用该脚本,它是完美的。动机当然是任何编程中最基本的规则之一(不是引用而是类似的):如果你在 2 个不同的地方有 "same code",那是不对的。