小编典典

詹金斯管道模板

jenkins

我们有几个Java项目。每个项目都有自己的交付管道。

所有管道都具有以下共同的步骤(简化):

  • 建立项目
  • 发布项目
  • 部署到测试环境
  • 部署到生产环境

项目管道仅在项目特定的属性(例如服务名称或测试和生产环境的IP地址)上有所不同。

问题是:我们如何避免所有项目都有共同之处?Jenkins的“管道作为代码”是否提供类似管道模板的内容?

我可以想象一个模板将在我们的项目管道中节省很多冗余代码/步骤。因此,设置新项目,维护管道,保持管道同步会容易得多。


阅读 236

收藏
2020-07-25

共1个答案

小编典典

对我们而言,一种行之有效的方法是将部分管道(所有项目具有相同的地方)或整个管道放入Jenkins共享库中

template.groovy在Jenkins共享库中,以下脚本()被定义为全局变量。该方法创建一个新的声明性管道(它也适用于脚本化管道语法)。所有项目特定的属性都通过templateParams地图提供。

/**
 * Defines a pipeline template (as a sample with one job parameter 
 * that should be common for all pipelines)
 */
def createMyStandardDeclarativePipeline(Map templateParams) {

    pipeline {
        agent any
        parameters {
            string(name: 'myInput', description: 'Some pipeline parameters')
        }
        stages {
            stage('Stage one') {
                steps {
                    script {
                        echo "Parameter from template creation: " + templateParams.someParam
                    }
                }
            }
            stage('Stage two') {
                steps {
                    script {
                        echo "Job input parameter: " + params.myInput
                    }
                }
            }
        }
    }
}

使用此全局变量,以下行从模板创建管道:

template.createMyStandardDeclarativePipeline(someParam: 'myParam')

结论

通过此概念,可以轻松定义管道模板并在多个项目中重复使用它们。

应用于问题中给出的示例,您可以使用简单的单行代码为项目创建交付管道:

template.createStandardDeliveryPipeline(serviceName: 'myService', 
                                        testEnv: '192.168.99.104', 
                                        productionEnv: '192.168.99.105')

更新(30-09-2017):
声明式管道1.2版现在正式支持在共享库中声明管道块。参见:https :
//jenkins.io/doc/book/pipeline/shared-libraries/#defining-declarative-
pipelines


更新(06-10-2017):
现在可以在此处找到扩展的示例:https : //jenkins.io/blog/2017/10/02/pipeline-templates-
with-shared-libraries/

2020-07-25