Jenkins pipeline shared library

Jenkinsfile

https://jenkins.io/doc/book/pipeline/jenkinsfile/html

Jenkins Pipeline is a suite of plugins that supports implementing and integrating continuous delivery pipelines into Jenkins. Pipeline provides an extensible set of tools for modeling simple-to-complex delivery pipelines "as code" via the Pipeline DSL.node

 

例子&教程:git

https://github.com/ciandcdgithub

http://www.cnblogs.com/itech/p/5875428.htmlide

 

以腳本形式定義 持續集成步驟,與界面配置相比, 其支持多業務融合, 具備更加的靈活性、擴展性,便於定位集成過程當中發現的問題。ui

可是腳本方式融合了若干業務後, 就徽致使腳本代碼繁雜, 不易於維護。 且不能達到業務配置和腳本公共邏輯分離的目的。this

爲解決這個問題, 存在兩種解決方案, 下面分別介紹。rest

 

load 加載方式

https://stackoverflow.com/questions/37800195/how-do-you-load-a-groovy-file-and-execute-itcode

Example.Groovyhtm

def exampleMethod() {
    println("exampleMethod")
}

def otherExampleMethod() {
    println("otherExampleMethod")
}
return this

JenkinsFile

node {
    // Git checkout before load source the file
    checkout scm

    // To know files are checked out or not
    sh '''
        ls -lhrt
    '''

    def rootDir = pwd()
    println("Current Directory: " + rootDir)

    // point to exact source file
    def example = load "${rootDir}/Example.Groovy"

    example.exampleMethod()
    example.otherExampleMethod()
}

 

shared library方式

https://jenkins.io/doc/book/pipeline/shared-libraries/

最爲推薦。

As Pipeline is adopted for more and more projects in an organization, common patterns are likely to emerge. Oftentimes it is useful to share parts of Pipelines between various projects to reduce redundancies and keep code "DRY"

https://stackoverflow.com/questions/38695237/create-resusable-jenkins-pipeline-script?noredirect=1

The Shared Libraries (docs) allows you to make your code accessible to all your pipeline scripts. You don't have to build a plugin for that and you don't have to restart Jenkins.

E.g. this is my library and this a Jenkinsfile that calls this common function.

The global library can be configured through the following means:

  • an @Library('github.com/...') annotation in the Jenkinsfile pointing to the URL of the shared library repo.
  • configured on the folder level of Jenkins jobs.
  • configured in Jenkins configuration as global library, with the advantage that the code is trusted, i.e., not subject to script security.

A mix of the first and last method would be a not explicitly loaded shared library that is then requested only using its name in the Jenkinsfile: @Library('mysharedlib').

相關文章
相關標籤/搜索