2017-04-10 53 views
2

我想將jenkinsfile中的內容分隔成一個groovy腳本。但它不能調用這些腳本: 以下是代碼:如何從Jenkins文件調用groovy腳本?

#!/usr/bin/env groovy 

node('test-node'){ 

  stage('Checkout') { 
    echo "${BRANCH_NAME} ${env.BRANCH_NAME}" 
    scm Checkout 

  } 

  stage('Build-all-targets-in-parallel'){ 

    def workspace = pwd() 
    echo workspace 
    parallel(
      'first-parallel-target' : 
       { 
         // Load the file 'file1.groovy' from the current directory, into a variable called "externalMethod". 
         //callScriptOne() 
         def externalMethod = load("file1.groovy") 
         // Call the method we defined in file1. 
          externalMethod.firstTest() 
       }, 
       'second-parallel-target' : 
      { 
         //callScriptTwo() 
         def externalMethod = load("file2.groovy") 
         // Call the method we defined in file1. 
         externalMethod.testTwo() 
        } 
    ) 
  } 
  stage('Cleanup workspace'){ 
    deleteDir() 
  } 
} 

file.groovy

#!groovy 

def firstTest(){ 

  node('test-node'){ 
     
    stage('build'){ 
      echo "Second stage" 
    } 
     
    stage('Cleanup workspace'){ 
      deleteDir() 
    } 
  } 
} 

貌似Jenkinsfile能夠調用file1.groovy但總是給我一個錯誤:

java.lang.NullPointerException: Cannot invoke method firstTest() on null object 
+0

我不認爲'負載(「file1.groovy」 )'找到你的groovy文件試圖調試。 – dynamo

回答

3

想從您的Jenkinsfile中提供方法,您需要執行以下操作

在你file1.groovy,返回引用的方法

def firstTest() { 
    // stuff here 
} 

def testTwo() { 
    //more stuff here 
} 
... 

return [ 
    firstMethod: this.&firstMethod, 
    testTwo: this.&testTwo 
] 

編輯

evaluate似乎並不需要

def externalMethod = evaluate readFile("file1.groovy") 

def externalMethod = evaluate readTrusted("file1.groovy") 

並經提到@Olia

def externalMethod = load("file1.groovy") 

應該工作

這裏是readTrusted參考。請注意,沒有參數替換被允許(不輕量級結賬)

輕質結帳:

If selected, try to obtain the Pipeline script contents directly from the SCM without performing a full checkout. The advantage of this mode is its efficiency; however, you will not get any changelogs or polling based on the SCM. (If you use checkout scm during the build, this will populate the changelog and initialize polling.) Also build parameters will not be substituted into SCM configuration in this mode. Only selected SCM plugins support this mode.

在爲我的作品至少

+0

你能幫我理解評估能做什麼嗎? –

+0

您對退貨的選擇是非常好的,非常依賴於功能。謝謝! –

+0

也許只有在使用'readFile'時才需要評估,所以'評估readFile(file)'與'load(file)'相同。你也可以使用'return this',但我更喜歡範圍界定。查看@Olia發佈的鏈接也表明,評估不是必需的。 – Rik