2017-07-25 456 views
2

我所擁有的是以下內容:描述here創建如何在Jenkins聲明式管道中的導入的groovy腳本中使用@Library?

  1. 全局共享庫。沒什麼特別的,vars文件夾中的一個腳本叫做deleteFile.groovy,試過了 - 工作。圖書館被稱爲myOneLib
  2. 稱爲firstPipe.groovy
@Library('myOneLib') _ 

def execute(String zCmakeListsPath){ 
    stage('some kind of stage 2') { 
     echo "Hello from stage 1 with " + zCmakeListsPath 
     echo "var attempt ${env.mySrcDir}" 

    } 
    stage('second stage'){ 
      echo "and one from stage 2" 
      echo "param was " + zCmakeListsPath 
      echo "var attempt ${env.myBuildDir}" 
      //call function from global lib 
      deleteFile 'for 3rd party global library now' 
    } 
} 

return this
管道腳本
  • 稱爲caller.groovy管道腳本正在調用firstPipe.groovy
  • pipeline { 
        agent any 
        environment { 
          myBuildDir = "thisShoulbBeBuild" 
          mySrcDir = "andHereIsSrc" 
         } 
        stages { 
         stage('first') { 
          steps { 
           script{ 
            echo 'beggining with ' + myBuildDir 
            def rootDir = pwd() 
            echo 'rootDir is ' + rootDir 
            def example = load "${rootDir}/fullPipe/firstPipe.groovy" 
            example.execute("rasAlGhul") 
           } 
          } 
         } 
        } 
    }

    現在,當我像這樣運行構建時,出現以下錯誤:

    ERROR: Could not find any definition of libraries [myOneLib]

    但是,當我只是將@Library('myOneLib') _行移動到caller.groovy的頂部一切正常。

    所以我的問題是如何在導入/包含腳本中使用@Library?還是有其他方式來指定全局庫?

    更多注意事項:caller.groovyfirstPipe.groovy在同一個git倉庫中,如果我消除了全局庫的使用情況,一切正常。我正在使用聲明式管道,並希望繼續這樣做。

    +1

    使用'library'步驟動態加載導入的腳本以處理Jenkins Groovy運行時如何工作的一些怪異可能更容易。 – mkobit

    +0

    @mkobit非常感謝提示,我不能相信我錯過了https://jenkins.io/doc/book/pipeline/shared-libraries/#loading-libraries-dynamically您是否會推薦您的評論來回答?或者我的問題太簡單明瞭了,我應該刪除它? :) – cantSleepNow

    +0

    我會添加它作爲答案。 – mkobit

    回答

    2

    對於此用例,使用library步驟在運行時動態加載它會更有意義。

    在你firstPipe.groovy,你可以這樣做:

    final myOneLib = library('myOneLib') 
    
    def execute(String zCmakeListsPath){ 
        stage('some kind of stage 2') { 
        echo "Hello from stage 1 with " + zCmakeListsPath 
        echo "var attempt ${env.mySrcDir}" 
    
        } 
        stage('second stage'){ 
        echo "and one from stage 2" 
        echo "param was " + zCmakeListsPath 
        echo "var attempt ${env.myBuildDir}" 
        //call function from global lib 
        myOneLib.deleteFile 'for 3rd party global library now' 
        } 
    } 
    
    return this 
    

    Loading libraries dynamically section of the Extending with Shared Libraries documentation

    +0

    如果我使用Jenkins Pipeline版本低於2.7,是否有任何解決方法? –

    +0

    @VitaliiVitrenko我假設你在談論['Pipeline Shared Groovy Libraries Plugin'](https://wiki.jenkins.io/display/JENKINS/Pipeline+Shared+Groovy+Libraries+Plugin),但是我不能想到一個優雅的。您可以要求用戶在他們的管道中使用'@ Library'將它帶入類路徑,或者將這些方法或類傳遞到其他級別。這些看起來像是一種拙劣的解決方法。 – mkobit

    相關問題