pipeline {
agent none
stages {
stage('Build') {
/* 描述了当前的状态 */
agent any
/* 运行的agent ,表示可以在任何node 节点上运行*/
steps { /* 步骤*/
checkout scm
sh'make'stashincludes:'**/target/*.jar',name:'app'}
}
stage('Test on Linux') {
agent {label'linux'}
steps {
unstash'app'sh'make check'}
post {
always {
junit'**/target/*.xml'}
}
}
stage('Test on Windows') {
agent {
label'windows'}
steps {
unstash'app'bat'make check'}
post {
always {
junit'**/target/*.xml'}
}
}
}
}
如果说要并行执行的话 就要添加parallel 步骤, 看如下的例子
Jenkinsfile (Scripted Pipeline)
stage('Build') {/* .. snip .. */}
stage('Test') {
parallellinux: {
node('linux') {
checkout scmtry{
unstash'app'sh'make check'}finally{
junit'**/target/*.xml'}
}
},windows: {
node('windows') {/* .. snip .. */}
}
}
Pipeline 的高阶语法
字符串插入和定义
Jenkins Pipeline uses rules identical to Groovy for string interpolatio Jenkins Pipeline使用
Groovy的语法来定义字符串。
defsinglyQuoted ='Hello'defdoublyQuoted ="World"
定义完了之后们,再次使用就要用$并且用双“来调用这个变量
defusername ='Jenkins'echo'Hello Mr. ${username}'echo"I said, Hello Mr.${username}"
上面的结果就会是
Hello Mr. ${username}
I said, Hello Mr. Jenkins
以下就是将环境变量接入到Jenkinsfile里面的使用方法
pipeline {
agent any
parameters {
string(name:'Greeting',defaultValue:'Hello',description:'How should I greet the world?')
}
stages {
stage('Example') {
steps {
echo"${params.Greeting}World!"}
}
}
}
环境变量的设置
BUILD_ID当前编译的ID.
JOB_NAME当前这个Job的名字
JENKINS_URLJenkins 的全局URL, 比如说 example.com:port/jenkins/ (NOTE: 只有你URL在 "System Configuration"设置才可见)
以下就是使用环境变量的Jenkinsfile的例子
Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
stages {
stage('Example') {
steps {
echo"Running${env.BUILD_ID}on${env.JENKINS_URL}"}
}
}
}
错误处理
通过 post sectionPipeline可以支持非常鲁棒的错误信息,它允许声明一系列 "post conditions",比如说: always
, unstable
, success
, failure
, and changed
.
以下的用例里面定义了出现错误的时候发送邮件等
Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
stages {
stage('Test') {
steps {
sh'make check'}
}
}
post {
always {
junit'**/target/*.xml'}
failure {
mailto: team@example.com,subject:'The Pipeline failed :('}
}
}