Jenkins pipeline之聲明式的jenkinsfile
內置的關鍵字
- pipeline : 是pipeline的跟節點
- agent: 定義piple使用哪個賬號在哪個機器上執行
- post: 定義pipeline最后執行的一組任務,支持多種條件判斷always, changed, fixed, regression, aborted,failure, success, unstable, unsuccessful, and cleanup.
- stages: 是多個stage的父節點。
- stage: 代表整個pipleline里的一個階段,stage里面才是具體的steps。
- steps: 定義在stage的內部,表示具體如何執行。
- environment: 定義公用的環境變量
- options: 定義pipeline或者plugin的參數設置。
- parameters: 定義了整個pipeline的外部參數,必須有默認值,用戶也可以在啟動時指定新的參數
- triggers: 定義如何觸發pipeline,例如cron,pollSCM,或者upstream。
- tools: 定義需要安裝的工具,且會自動加入到PATH
- input: 允許pipeline與用戶交互,等待用戶確認然后繼續。
- when: 條件語句
pipeline的實例代碼
其實還是非常直觀易懂的:
pipeline {
agent {
node {
label 'DEBIAN8'
}
}
triggers {
cron('H */4 * * 1-5')
}
environment {
ARTIFACTORY_URL = 'https://path.to.artifacts/some-registry'
}
options {
disableConcurrentBuilds()
retry(1)
skipStagesAfterUnstable()
timeout(time: 10, unit: 'MINUTES')
skipDefaultCheckout()
buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '1'))
}
tools {
/**
* Predefined environment variables MAVEN3 and JDK-1.8
*/
maven 'MAVEN3'
jdk 'JDK-1.8'
}
stages {
/**
* Initialization check for Java and Maven
*/
stage('Initialization') {
steps {
sh '''
java -version
mvn -version
'''
}
}
/**
* Checkout source code from Github on any of the GIT nodes
*/
stage('Checkout') {
steps {
checkout scm
}
}
/**
* Compile the Maven project
*/
stage('Build') {
steps {
sh 'mvn clean install'
}
}
/**
* Trigger this in PRs, don't run on master or release branches
*/
stage('Package') {
when {
changeRequest()
}
steps {
sh 'mvn clean package -DskipTests'
}
}
/**
* Only run this on master and release branches
*/
stage('Deploy') {
when {
branch 'master'
}
environment {
DEPLOYER = credentials('deployer')
}
steps {
sh 'mvn clean deploy'
}
}
/**
* Clean workspace
*/
stage('Clean') {
steps {
cleanWs()
}
}
}
post {
always {
echo 'I will always say Hello again!'
}
}
}
常見的options
我們來解釋一下上面常用的option的用途:
- disableConcurrentBuilds():一時間最多只允許一個pipeline運行,如果前面的仍在運行, 后面的將會等待狀態。
- retry(1): 失敗了,重試一次。
- skipStagesAfterUnstable():如果某個stage為unstable狀態,則忽略后面的任務,直接退出。
- timeout(time: 10, unit: 'MINUTES'):10分鍾的超時設置。
- skipDefaultCheckout(): 忽略默認的checkout。
- buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '1')): 保留最新的10個build log和1個artifact。
參考:
https://medium.com/@brianrthompson/scripted-vs-declarative-pipelines-which-to-choose-c6af403f1e97