How to configure a Jenkins 2 Pipeline so that Jenkinsfile uses a predefined variable

前端 未结 2 1331
北恋
北恋 2020-12-22 03:19

I have several projects that use a Jenkinsfile which is practically the same. The only difference is the git project that it has to checkout. This forces me to have one Jenk

2条回答
  •  旧巷少年郎
    2020-12-22 03:30

    You can use the Pipeline Shared Groovy Library plugin to have a library that all your projects share in a git repository. In the documentation you can read about it in detail.

    If you have a lot of Pipelines that are mostly similar, the global variable mechanism provides a handy tool to build a higher-level DSL that captures the similarity. For example, all Jenkins plugins are built and tested in the same way, so we might write a step named 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: "..."
        }
    }
    

    Assuming the script has either been loaded as a Global Shared Library or as a Folder-level Shared Library the resulting Jenkinsfile will be dramatically simpler:

    Jenkinsfile (Scripted Pipeline)

    buildPlugin {
        name = 'git'
    }
    

    The example shows how a jenkinsfile passes name = git to the library. I currently use a similar setup and am very happy with it.

提交回复
热议问题