Jenkins pipeline 語法詳解

原文地址http://www.cnblogs.com/fengjian2016/p/8227532.htmlhtml

pipeline 是一套運行於jenkins上的工做流框架,將本來獨立運行於單個或者多個節點的任務鏈接起來,實現單個任務難以完成的複雜流程編排與可視化。java

pipeline 是jenkins2.X 最核心的特性, 幫助jenkins 實現從CI 到 CD與 DevOps的轉變node

 

pipeline 提供一組可擴展的工具, 經過 pipeline domain specific language syntax 能夠到達pipeline as code 目的web

pipiline as code :  jenkinsfile 存儲在項目的 源代碼庫docker

 

爲何要使用pipelineexpress

1. 代碼: pipeline 以代碼的形式實現,經過被撿入源代碼控制, 使團隊可以編譯,審查和迭代其cd流程api

2 可連續性: jenkins 重啓 或者中斷後都不會影響pipeline job框架

3.停頓: pipeline 能夠選擇中止並等待人工輸入或者批准,而後在繼續pipeline運行dom

4.多功能:  pipeline 支持現實世界的複雜CD要求, 包括fork、join子進程,循環和並行執行工做的能力ide

5.可擴展: pipeline 插件支持其DSL的自動擴展以及其插件集成的多個選項。

 

 

jenkins pipeline 入門

pipeline 腳本是有groovy 語言實現的

-無需專門學習 groovy

 

pipeline 支持兩種語法

  -  Declarative 聲明式

  -  Scripted pipeline  腳本式

 

如何建立基本的pipeline

  -  直接在jenkins web ui 網頁界面輸入腳本

  -  經過常見一個jenkins 能夠檢入項目的源代碼管理庫

 

 

Declarativ 聲明式 pipeline

聲明式pipeline 基本語法和表達式遵循 groovy語法,可是有如下例外:

  -  聲明式pipeline 必須包含在固定格式的pipeline{} 塊內

  -  每一個聲明語句必須獨立一行, 行尾無需使用分號

  -   塊(Blocks{}) 只能包含章節(Sections),指令(Directives),步驟(Steps),或者賦值語句

  -  屬性引用語句被視爲無參數方法調用。 如input()

 

塊(Blocks{})

  -  由大括號括起來的語句: 如 Pipeline{}, Sections{}, parameters{}, script{}

章節(Sections)

  -  一般包括一個或者多個指令或步驟 如 agent,post,stages,steps

指令(Directives)

  -  environment, options, parameters, triggers, stage, tools, when

步驟(steps)

  -  執行腳本式pipeline, 如script{}

 

 

agent

須要 必須存在,agent必須在pipeline塊內的頂層定義,可是stage內是否使用爲可選
參數 any/none/label/node/docker/dockerfile
經常使用參數 label/customWorkspace/reuseNode
展現:
agent { label 'this k8s-api-label'} 

agent {

    node{

      label ' this is k8sapi-label'

      customWorkspace '/some/other/path'

    }

}

agent {

     docker {

        image 'im-web'

        label 'this is k8sapi-label'

        args '-v /tmp:/tmp'

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

# customWorkspace  node節點的工做空間

 

 

post

須要 否,用於pipeline的最外層或者stage{}中
參數
經常使用選項

構建後操做的內置斷定條件

always,changed,failure,sucess,unstable,aborted

展現:
複製代碼
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
    post {
        always {
            echo 'I will ........!'
        }
    }
}
複製代碼

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

stages

須要 是,包括順序執行的一個或者多個stage命令
參數
經常使用選項

構建後操做的內置斷定條件

always,changed,failure,sucess,unstable,aborted

展現:
複製代碼
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
      stage('echo') {
          steps {
              echo 'I will ........!'
          }
      }
}
複製代碼

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

steps

須要 是,steps位於stage指令塊內部,包括一個或者多個step
參數
說明

僅有一個step的狀況下能夠忽略關鍵字step及其{}

展現:
複製代碼
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
      stage('echo') {
          steps {
              echo 'I will ........!'
          }
      }
}
複製代碼

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Directives (指令)

 

environment指令指定一系列鍵值對,這些鍵值對將被定義爲全部step或stage-specific step的環境變量,具體取決於environment指令在Pipeline中的位置。
該指令支持一種特殊的方法credentials(),能夠經過其在Jenkins環境中的標識符來訪問預約義的憑據。
對於類型爲「Secret Text」的憑據,該 credentials()方法將確保指定的環境變量包含Secret Text內容;對於「標準用戶名和密碼」類型的憑證,指定的環境變量將被設置爲username:password。

 

environment

須要 是,environment 定義了一組全局的環境變量鍵值對
參數
說明

存在於pipeline{} 或者stage指令內,

注意特殊方法credentials() ,能夠獲取jenkins中預約義的憑證實文內容

展現:
複製代碼
pipeline {
    agent any
    
    environment {
        SONAR_SERVER = 'http://172.16.230.171:9000'
    }
    
    stages {
        stage('Example') {
            steps {
                echo "${SONAR_SERVER}"
            }
        }
    }
}
複製代碼

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

options

buildDiscarder
    pipeline保持構建的最大個數。例如:options { buildDiscarder(logRotator(numToKeepStr: '1')) }
  disableConcurrentBuilds
    不容許並行執行Pipeline,可用於防止同時訪問共享資源等。例如:options { disableConcurrentBuilds() }
  skipDefaultCheckout
    默認跳過來自源代碼控制的代碼。例如:options { skipDefaultCheckout() }
  skipStagesAfterUnstable
    一旦構建狀態進入了「Unstable」狀態,就跳過此stage。例如:options { skipStagesAfterUnstable() }
  timeout
    設置Pipeline運行的超時時間。例如:options { timeout(time: 1, unit: 'HOURS') }
  retry
    失敗後,重試整個Pipeline的次數。例如:options { retry(3) }
  timestamps
    預約義由Pipeline生成的全部控制檯輸出時間。例如:options { timestamps() }

 

options

須要 否,預約義pipeline專有的配置信息,僅可定義一次
參數
說明
authorizationMatrix, buildDiscarder, catchError, disableConcurrentBuilds, overrideIndexTriggers, 
retry, script, skipDefaultCheckout, skipStagesAfterUnstable, timeout, waitUntil, withContext,
withCredentials, withEnv, ws
展現: 設置構建超時時間 爲1個小時
複製代碼
pipeline {
    agent any
    
    options {
        timeout(time:1, unit: 'HOURS')
    }
    
    environment {
        SONAR_SERVER = 'http://172.16.230.171:9000'
        JAVA_HOME='/data/jdk'
    }
    
    stages {
        stage('sonarserver') {
            steps {
                echo "${SONAR_SERVER}"
            }
        }
        stage('javahome') {
            steps {
                echo "${JAVA_HOME}"
            }
        }
    }
}
複製代碼

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

parameters

 parameters指令提供用戶在觸發Pipeline時的參數列表。這些參數值經過該params對象可用於Pipeline步驟

可用參數
  string
    A parameter of a string type, for example: parameters { string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: '') }
  booleanParam
    A boolean parameter, for example: parameters { booleanParam(name: 'DEBUG_BUILD', defaultValue: true, description: '') }
  目前只支持[booleanParam, choice, credentials, file, text, password, run, string]這幾種參數類型,其餘高級參數化類型還需等待社區支持。

 

parameters

須要 否,定義參數化構建的參數
參數
說明
booleanParam,choice,file,text,password,run,string
示例

 

複製代碼
pipeline {
    agent any
    
    options {
        timeout(time:1, unit: 'HOURS')
    }
    
    parameters {
        choice(name:'PerformMavenRelease',choices:'False\nTrue',description:'desc')
     //   password(name:'CredsToUse',defaultValue:'',description:'A password to build with')
    }
    
    environment {
        SONAR_SERVER = 'http://172.16.230.171:9000'
        JAVA_HOME='/data/jdk'
    }
    
    stages {
        stage('sonarserver') {
            steps {
                echo "${SONAR_SERVER}"
            }
        }
        stage('javahome') {
            steps {
                echo "${JAVA_HOME}"
            }
        }
        stage('get parameters') {
            steps {
                echo "${params.PerformMavenRelease}"
            }
        }        
    }
}
複製代碼

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

調用定義的參數, 須要使用 params.PerformMavenRelease

 

 

 

 

 

 

 

 

triggers

 

triggers指令定義了Pipeline自動化觸發的方式。對於與源代碼集成的Pipeline,如GitHub或BitBucket,triggers可能不須要基於webhook的集成也已經存在。目前只有兩個可用的觸發器:cron和pollSCM。

triggers

須要 否,定義pipeline被自動觸發的方式
參數
說明
cron,pollSCM,upstream
示例

 

複製代碼
pipeline {
    agent any
    
    options {
        timeout(time:1, unit: 'HOURS')
    }
    
    parameters {
        choice(name:'PerformMavenRelease',choices:'False\nTrue',description:'desc')
     //   password(name:'CredsToUse',defaultValue:'',description:'A password to build with')
    }
    
    environment {
        SONAR_SERVER = 'http://172.16.230.171:9000'
        JAVA_HOME='/data/jdk'
    }
    
   triggers {
     cron('H 4/* 0 0 1-5')
}
stages { stage('sonarserver') { steps { echo "${SONAR_SERVER}" } } stage('javahome') { steps { echo "${JAVA_HOME}" } } stage('get parameters') { steps { echo "${params.PerformMavenRelease}" } } } }
複製代碼

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

when

  when指令容許Pipeline根據給定的條件肯定是否執行該階段。該when指令必須至少包含一個條件。若是when指令包含多個條件,則全部子條件必須爲stage執行返回true。這與子條件嵌套在一個allOf條件中相同(見下面的例子)。
更復雜的條件結構可以使用嵌套條件建:not,allOf或anyOf。嵌套條件能夠嵌套到任意深度

 

 內置條件
  branch
    當正在構建的分支與給出的分支模式匹配時執行,例如:when { branch 'master' }。請注意,這僅適用於多分支Pipeline。
  environment
    當指定的環境變量設置爲給定值時執行,例如: when { environment name: 'DEPLOY_TO', value: 'production' }
  expression
    當指定的Groovy表達式求值爲true時執行,例如: when { expression { return params.DEBUG_BUILD } }
  not
    當嵌套條件爲false時執行。必須包含一個條件。例如:when { not { branch 'master' } }
  allOf
    當全部嵌套條件都爲真時執行。必須至少包含一個條件。例如:when { allOf { branch 'master'; environment name: 'DEPLOY_TO', value: 'production' } }
  anyOf
    當至少一個嵌套條件爲真時執行。必須至少包含一個條件。例如:when { anyOf { branch 'master'; branch 'staging' } }

 

when

須要
參數
說明
inside a stage directive
複製代碼
pipeline {
    agent any
    stages {
        stage('Example Build') {
            steps {
                echo 'Hello World'
            }
        }
        stage('Example Deploy') {
            when {
                allOf {
                    branch 'production'
                    environment name: 'DEPLOY_TO', value: 'production'
                }
            }
            steps {
                echo 'Deploying'
            }
        }
    }
}
複製代碼

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Parallel(並行)

 

 Declarative Pipeline近期新增了對並行嵌套stage的支持,對耗時長,相互不存在依賴的stage能夠使用此方式提高運行效率。除了parallel stage,單個parallel裏的多個step也能夠使用並行的方式運行。

複製代碼
pipeline {
    agent any
    stages {
        stage('Non-Parallel Stage') {
            steps {
                echo 'This stage will be executed first.'
            }
        }
        stage('Parallel Stage') {
            when {
                branch 'master'
            }
            parallel {
                stage('Branch A') {
                    agent {
                        label "for-branch-a"
                    }
                    steps {
                        echo "On Branch A"
                    }
                }
                stage('Branch B') {
                    agent {
                        label "for-branch-b"
                    }
                    steps {
                        echo "On Branch B"
                    }
                }
            }
        }
    }
}
複製代碼

 

 

 

 

 

 

 

變量傳遞

1. 自定義變量(局部)

def username = 'jenkins'

echo "hello Mr.${username}"

 

 

2. 環境變量

withEnv(['JAVA_HOME=/data/jdk']) {

  sh '$JAVA_HOME/bin/start.sh'

}

 

3. 環境變量(全局)

environment {
        JAVA_HOME='/data/jdk'        
}

echo " java path $JAVA_HOME"

 

4. 參數化構建(全局)

複製代碼
parameters  {
        string(name: 'GIT_BRANCH', defaultValue: 'master', description: 'default build branch')  
}


調用:
 echo  "${params.name}" 
複製代碼

 

 

判斷:

1.when 僅用於stage內部

2. when 的內置條件

複製代碼
1). when {branch 'master'}  #當是master的時候,才執行某些事情                                            
2). when {envionment name:'DEPLOY_TO',value:'production'}  #當環境變量name 的值是production的時候,才執行某些事情
3). when {expression {return params.DEBUG_BUILD}}   #表達式的返回值是真的狀況下,才執行
4). when {not {branch 'master'}}            #不是master的狀況下,執行
5). when {allOf {branch 'master'; environment name: 'DEPLOY_TO',value:'production'}} #當大括號中全部的項都成立,纔去作某些事情
6). when {anyOf {branch 'master'; branch 'staging'}}  #只要知足大括號裏面的某一個條件,纔去作某些事情
複製代碼
相關文章
相關標籤/搜索