2017-04-07 17 views
1

我有几个使用Jenkinsfile的项目几乎相同。唯一的区别是它必须签出的git项目。这迫使我必须每个项目一个Jenkinsfile虽然可以共享相同的一个:如何配置Jenkins 2管道,以便Jenkinsfile使用预定义变量

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的位置作为创造就业过程中的变量,所以我可以重复使用相同的Jenkinsfile?

... 
    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访问它。

缺点是用户被要求用默认值开始构建或者改变它。我需要对用户透明。有没有办法做到这一点?

回答

1

你可以使用Pipeline Shared Groovy Library plugin有一个库,所有的项目在一个git仓库中共享。在documentation你可以详细阅读它。

如果您有大量类似的管道,全局变量机制提供了一个方便的工具来构建捕获相似性的更高级DSL。例如,所有詹金斯插件构建和以同样的方式进行测试,所以我们可以写一个名为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: "..." 
    } 
} 

假设脚本已经装载作为一个全球共享库 或文件夹层次的共享库所得Jenkinsfile将 大大简化:

Jenkinsfile(脚本管道)

buildPlugin { 
    name = 'git' 
} 

该示例显示jenkinsfile如何将name = git传递给库。 我目前使用类似的设置,我很高兴。

+0

感谢您的建议,我会在接下来的几天尝试它,并回来一些反馈。 – codependent

+0

考虑使用多分支管道。然后jenkins会为每个分支显示一个单独的subjob。这是一个更好的可视化,您可以开始为每个分支手动构建。 – herm

0

而是在每个Git仓库有Jenkinsfile的,你可以从你在哪里得到的共同Jenkinsfile额外的Git仓库 - 这一点使用流水线式作业并从SCM选项管道脚本时的作品。这样詹金斯在检出用户回购之前检出你拥有常见Jenkins文件的回购站。

如果作业可以被自动触发,您可以在每个git仓库中创建一个post-receive钩子,该仓库用repo作为参数调用Jenkins管道,以便用户不必手动运行输入的作业回购作为参数(GIT_REPO_LOCATION)。

如果作业不能自动触发,我能想到的最不讨厌的方法是使用选择参数,其中有一个存储库列表而不是String参数。

相关问题