2017-04-24 95 views
4

我正在創建一個樣本詹金斯管道,這裏是代碼。詹金斯管道如果還沒有工作

pipeline { 
    agent any 

    stages {  
     stage('test') { 
      steps { 
       sh 'echo hello' 
      }    
     } 
     stage('test1') { 
      steps { 
       sh 'echo $TEST' 
      }    
     } 
     stage('test3') { 
      if (env.BRANCH_NAME == 'master') { 
       echo 'I only execute on the master branch' 
      } else { 
       echo 'I execute elsewhere' 
      }       
     }   
    } 
} 

這條管道失敗,下面的錯誤日誌

Started by user admin 
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: 
WorkflowScript: 15: Not a valid stage section definition: "if (env.BRANCH_NAME == 'master') { 
       echo 'I only execute on the master branch' 
      } else { 
       echo 'I execute elsewhere' 
      }". Some extra configuration is required. @ line 15, column 9. 
      stage('test3') { 
     ^

WorkflowScript: 15: Nothing to execute within stage "test3" @ line 15, column 9. 
      stage('test3') { 
     ^

但是,當我執行下面的例子from this url,它成功地執行並打印else部分。

node { 
    stage('Example') { 
     if (env.BRANCH_NAME == 'master') { 
      echo 'I only execute on the master branch' 
     } else { 
      echo 'I execute elsewhere' 
     } 
    } 
} 

唯一的區別我可以看到的是,在工作示例沒有stages但對我來說是這樣。

這裏有什麼錯,任何人都可以請建議?

回答

16

你的第一次嘗試使用聲明的管道,而第二工作一個是使用腳本管道。你需要附上一個步驟聲明步驟,你不能,如果在聲明頂級步驟中使用,所以你需要用它在腳本中的一步。這裏有一個工作版本聲明:

pipeline { 
      agent any 

      stages { 
        stage('test') { 
          steps { 
            sh 'echo hello' 
          } 
        } 
        stage('test1') { 
          steps { 
            sh 'echo $TEST' 
          } 
        } 
        stage('test3') { 
          steps { 
            script { 
              if (env.BRANCH_NAME == 'master') { 
                echo 'I only execute on the master branch' 
              } else { 
                echo 'I execute elsewhere' 
              } 
            } 
          } 
        } 
      } 
    } 

您可以通過使用「時,」簡化這個和潛在的避免if語句(只要你不需要別人)。請參閱https://jenkins.io/doc/book/pipeline/syntax/上的「何時指令」。你也可以使用jenkins rest api來驗證jenkinsfiles。它超級甜美。在詹金斯的聲明式管道中玩得開心!

+0

謝謝你這麼多,一爲答案,+1聲明管線和腳本管道,一爲REST API的建議。實際上,我需要如果和其他這就是爲什麼我使用它。 – Shahzeb

0

它需要一個比特重新排列的,但when做得很好,以取代上述條件句。以上是使用聲明性語法編寫的示例。請注意0​​階段現在是兩個不同的階段。一個在主分支上運行,另一個在其他任何地方運行。

stage ('Test 3: Master') { 
    when { branch 'master' } 
    steps { 
     echo 'I only execute on the master branch.' 
    } 
} 

stage ('Test 3: Dev') { 
    when { not { branch 'master' } } 
    steps { 
     echo 'I execute on non-master branches.' 
    } 
}