## 基础语法
>什么是pipeline
Jenkins Pipeline是一套插件,支持将连续输送Pipeline实施和整合到Jenkins。Pipeline提供了一组可扩展的工具,用于通过PipelineDSL为代码创建简单到复杂的传送Pipeline
>定义pipeline
例如:执行脚本失败重试5次,但是执行时间不超过3分钟
```
pipeline {
agent any
stages {
stage('Deploy') {
steps {
timeout(time: 3, unit: 'MINUTES') {
retry(5) {
sh './flakey-deploy.sh'
}
}
}
}
}
}
```
>environment
示例:定义变量并调用变量
```
pipeline{
agent { label "cm-linux" }
environment {
name = 'allen'
}
stages{
stage("Deploy"){
steps{
deleteDir()
echo "${name}"
}
}
stage("Python version"){
steps{
sh "python --version"
}
}
}
}
```
>pipeline post
post部分在执行完pipeline结束,可以添加通知或清理的操作。
例如:
```
pipeline{
agent any
stages{
stage('Deploy'){
steps{
sh 'ls /root'
}
}
}
post{
always{
echo 'aaa'
}
success{
echo 'bbb'
}
unstable{
echo 'ccc'
}
failure{
echo 'ddd'
}
changed{
echo 'eee'
}
}
}
```
pipeline执行失败发送邮件,例如:
```
post{
failure{
mail to: 'baocai.guo@qq.com',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.BUILD_URL}"
}
}
```
>使用证书
示例:
```
environment {
AWS_ACCESS_KEY_ID = credentials('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = credentials('AWS_SECRET_ACCESS_KEY')
}
```
>when
该when指令允许Pipeline根据给定的条件确定是否执行该阶段。该when指令必须至少包含一个条件。如果when指令包含多个条件,则所有子条件必须为舞台执行返回true。
when内置条件:
|内置参数|代码示例|描述|
|:---:|:---:|:---:|
|branch|`when { branch 'master' }`|当代码分支为master时执行stage|
|environment|`when { environment name: 'name' value: 'allen' }`|当env name为allen时执行stage|
|expression|`when { expression { return params.DEBUG_BUILD } }`|当表达式值为true执行stage|
|not|`when { not { branch 'master' } }`|当嵌套条件为false时,执行stage。必须包含一个条件|
|allOf|`when { allOf { branch 'master' } }`|当所有嵌套条件为true时,执行stage。必须包含一个条件|
|anyOf|`when { anyOf { branch 'master' } }`|当至少一个嵌套条件为true时,执行stage。必须包含一个条件|
>script
在pipeline执行shell script,例如:
```
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello World'
script {
def browsers = ['chrome', 'firefox']
for (int i = 0; i < browsers.size(); ++i) {
echo "Testing the ${browsers[i]} browser"
}
}
}
}
}
}
```
>flow control
流程控制,例如:
```
pipeline {
agent { label "cm-linux" }
stages{
stage('Example') {
if (env.BRANCH_NAME == 'master') {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
}
}
}
}
```
```
pipeline{
agent { label "cm-linux" }
stages{
stage("Build Package"){
when {
expression {
if ( params.enable_build_package ){
echo "Build Package"
return true
}else{
echo "Skip Build Package"
return false
}
}
}
steps{
echo "Start Build Package"
}
}
}
}
```