Jenkins 2 Pipleline的简单教程(二)
2018-07-13
Jenkins Pipeline支持两种语法,一种Declarative Pipeline(声明式),一种Scripted Pipeline(脚本式)。 声明式的Pipeline限制用户使用严格的预选定义的结构,是一种声明式的编程模型,对比脚本式的Pipeline学习起来更加简单;脚本式的Pipeline限制比较少,结构和语法的限制由Groovy本身决定,是一种命令式的编程模型。
关于Pipeline的语法在编写Pipeline的过程中,查看这里Pipeline Syntax就够了。
编写第一个Declarative Pipeline:
1pipeline {
2 agent { label 'jenkins-slave' }
3 stages {
4 stage('build') {
5 steps {
6 sh 'echo hello'
7 }
8 }
9 }
10}
运行多个Step的Pipeline:
1pipeline {
2 agent { label 'jenkins-slave' }
3 stages {
4 stage('build') {
5 steps {
6 sh 'echo step1'
7 sh '''
8 echo step2-1
9 echo step2-2
10 '''
11 }
12 }
13 }
14}
retry和timeout wrap step:
1pipeline {
2 agent { label 'jenkins-slave' }
3 stages {
4 stage('build') {
5 steps {
6 retry(3) {
7 sh 'echo deploy'
8 }
9 timeout(time: 5, unit: 'SECONDS') {
10 sh 'echo healthcheck'
11 sh 'sleep 4'
12 }
13 }
14 }
15 }
16}
post完成:
1pipeline {
2 agent { label 'jenkins-slave' }
3 stages {
4 stage('Test') {
5 steps {
6 sh 'echo "Fail!"; exit 1'
7 }
8 }
9 }
10 post {
11 always {
12 echo 'This will always run'
13 }
14 success {
15 echo 'This will run only if successful'
16 }
17 failure {
18 echo 'This will run only if failed'
19 }
20 unstable {
21 echo 'This will run only if the run was marked as unstable'
22 }
23 changed {
24 echo 'This will run only if the state of the Pipeline has changed'
25 echo 'For example, if the Pipeline was previously failing but is now successful'
26 }
27 }
28}
设置环境变量:
1pipeline {
2 agent { label 'jenkins-slave' }
3
4 environment {
5 DISABLE_AUTH = 'true'
6 DB_ENGINE = 'sqlite'
7 }
8
9 stages {
10 stage('Build') {
11 steps {
12 sh 'printenv'
13 }
14 }
15 }
16}
将credentials设置为环境变量值:
1pipeline {
2 agent { label 'jenkins-slave' }
3
4 environment {
5 SONAR_LOGIN = credentials('sonarLogin')
6 }
7
8 stages {
9 stage('Build') {
10 steps {
11 sh 'printenv'
12 }
13 }
14 }
15}
清理和通知:
1pipeline {
2 agent { label 'jenkins-slave' }
3 stages {
4 stage('build') {
5 steps {
6 timeout(time: 1, unit: 'SECONDS') {
7 sh 'sleep 2'
8 }
9 }
10 }
11 }
12 post {
13 failure {
14 mail to: '[email protected]',
15 subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
16 body: "Something is wrong with ${env.BUILD_URL}"
17 }
18 }
19}