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

前端 未结 2 1330
北恋
北恋 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:27

    Instead of having a Jenkinsfile in each Git repository, you can have an additional git repository from where you get the common Jenkinsfile - this works when using Pipeline type Job and selecting the option Pipeline script from SCM. This way Jenkins checks out the repo where you have the common Jenkinsfile before checking out the user repo.

    In case the job can be triggered automatically, you can create a post-receive hook in each git repo that calls the Jenkins Pipeline with the repo as a parameter, so that the user does not have to manually run the job entering the repo as a parameter (GIT_REPO_LOCATION).

    In case the job cannot be triggered automatically, the least annoying method I can think of is having a Choice parameter with a list of repositories instead of a String parameter.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题