2017-04-07 22 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參數。

相關問題