如何配置Jenkins 2管道,以便Jenkinsfile使用预定义的变量

时间:2017-04-07 12:26:12

标签: jenkins jenkins-pipeline continuous-delivery jenkins-2

我有几个使用Jenkins文件的项目实际上是相同的。唯一的区别是它必须结帐的git项目。这迫使我每个项目都有一个Jenkins文件,尽管它们可以共享同一个:

node{
    def mvnHome = tool 'M3'
    def artifactId
    def pomVersion

    stage('Commit Stage'){
        echo 'Downloading from Git...'
        git branch: 'develop', credentialsId: 'xxx', url: 'https://bitbucket.org/xxx/yyy.git'
        echo 'Building project and generating Docker image...'
        sh "${mvnHome}/bin/mvn clean install docker:build -DskipTests"
    ...

有没有办法在创建作业期间将git位置预先配置为变量,这样我可以重用相同的Jenkins文件?

...
    stage('Commit Stage'){
        echo 'Downloading from Git...'
        git branch: 'develop', credentialsId: 'xxx', url: env.GIT_REPO_LOCATION
    ...

我知道我可以这样设置:

此项目已参数化 - >字符串参数 - > GIT_REPO_LOCATION,默认= http://xxxx,并使用env.GIT_REPO_LOCATION访问它。

缺点是用户被要求使用默认值启动构建或更改它。我需要它对用户来说是透明的。有办法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用Pipeline Shared Groovy Library plugin拥有一个库,您的所有项目都在git存储库中共享。在documentation中,您可以详细了解它。

  

如果你有很多大致相似的管道,全局变量机制提供了一个方便的工具来构建一个捕获相似性的更高级别的DSL。例如,所有Jenkins插件都以相同的方式构建和测试,因此我们可以编写一个名为buildPlugin的步骤:

// vars/buildPlugin.groovy
def call(body) {
    // evaluate the body block, and collect configuration into the object
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()

    // now build, based on the configuration provided
    node {
        git url: "https://github.com/jenkinsci/${config.name}-plugin.git"
        sh "mvn install"
        mail to: "...", subject: "${config.name} plugin build", body: "..."
    }
}
  

假设脚本已作为全局共享库加载   或者作为文件夹级共享库,生成的Jenkins文件将是   简单得多:

     

Jenkinsfile(脚本管道)

buildPlugin {
    name = 'git'
}

该示例显示了jenkinsfile如何将name = git传递给库。 我目前使用类似的设置,对此非常满意。

答案 1 :(得分:0)

不是在每个Git存储库中都有一个Jenkins文件,而是可以从另外的git存储库获取公共Jenkins文件 - 这在使用管道类型作业并选择选项管道时有效来自SCM的脚本。这样Jenkins会在检出用户仓库之前检出你拥有公共Jenkinsfile的仓库。

如果可以自动触发作业,您可以在每个git仓库中创建一个后接收挂钩,该仓库以repo作为参数调用Jenkins管道,这样用户就不必手动运行作业进入repo作为参数(GIT_REPO_LOCATION)。

如果作业无法自动触发,我能想到的最烦人的方法是使用 Choice参数,其中包含存储库列表而不是String参数。

相关问题