基本结构
pipeline {
agent {
label 'jenkins-slave'
}
//构建参数
parameters {
//result = sh(script: "declare -l U_Proj_num=${${PROD_NAME}:0:3}", returnStdout: true).trim()
string(name: "NAME", defaultValue: "test")
choice(name: 'MODE', choices: ['S'], description: '')
}
//显示编译时间
options {
timestamps()
}
stages {
stage('set global stages environment') {
steps {
script {
println(env)
if(env.PROD_NAME.length() == 5) {
env['U_Proj_num'] = env.PROD_NAME[0..2]
}else{
env['U_Proj_num'] = env.PROD_NAME[0..3]
}
println env.U_Proj_num
if(fileExists("${WORKSPACE}/version.txt")) {
def version = readFile("${WORKSPACE}/version.txt")
env['BUILD_DISPLAY_NAME'] = version.toString()
println env.BUILD_DISPLAY_NAME
}
currentBuild.displayName = env.BUILD_DISPLAY_NAME
}
}
}
stage('sync code') {
steps('sync source code') {
script {
echo "sync source code"
}
}
}
stage('get build version') {
steps {
script {
sh "python ${WORKSPACE}/Make.py"
sh 'echo "get version"'
}
}
}
stage('build QNX') {
steps {
}
}
stage('build image') {
parallel {
stage('build android') {
steps {
script {
echo "build android"
sh(script: """
cd ${WORKSPACE}/Android
rm start_build.sh
""")
}
}
}
stage('build') {
steps {
echo "build"
//build job: 'test', parameters:[string(name: 'BUILD_VERSION', value: "env.BUILD_NAME")]
}
}
}
}
stage('package images') {
//environment {
// BUILD_DISPLAY_NAME = "${env.BUILD_NAME}"
//}
steps {
script {
sh(script: """
rm -rf *.tar.gz
""")
}
}
}
}
post {
success {
echo "build success"
mail body: '${JOB_NAME}',
subject: '${JOB_NAME}',
attachmentsPattern: 'version.txt',
from: '',
to: 'email'
}
failure {
echo "build failed"
}
}
}
Pipeline 从头pipeline开始,基本组织架构由label、stages、stage、steps、post等组成。
agent:编译运行的Jenkins节点,写在开头表示全局使用该节点,也可以配置在单个stage中
stages:描述构建开始的位置,大部分构建内容放在这个里面
stage:构建步骤,按先后顺序执行,前面步骤出错,则停止执行后续stage
parallel:并行执行标志,定义在stage下面,同时下面又可以定义多个stage,处于parallel下面的stage可以并行执行,而不是按顺序,单个执行报错不会终止其它同级stage任务
post:构建结束后执行,一般用来发邮件之类的;常常定义在pipeline最后面,也可以定义在单个stage中,用来处理编译报错问题
参数化构建
string
字符串类型的参数, 例如: parameters { string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: '') }
booleanParam
布尔参数, 例如: parameters { booleanParam(name: 'DEBUG_BUILD', defaultValue: true, description: '') }
password
A password parameter, for example: parameters { password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'A secret password') }
text
A text parameter, which can contain multiple lines, for example: parameters { text(name: 'DEPLOY_TEXT', defaultValue: 'One\nTwo\nThree\n', description: '') }
执行groovy脚本
pipeline支持groovy脚本编写运行步骤,例如
if(env.PROD_NAME.length() == 5) {
env['U_Proj_num'] = env.PROD_NAME[0..2]
}else{
env['U_Proj_num'] = env.PROD_NAME[0..3]
}
由于不同的Jenkins版本有不同的pipeline对应版本,带有的groovy版本也会不同,所以有些版本语法会有差别,比如我这个Jenkins版本(2.263.1)的env.PROD_NAME.length是会报错的,需要写成这样:
def name = env.PROD_NAME
if(name.length == 5) {
echo "name"
}
使用pipeline环境变量
pipeline中的环境变量用env来管理和使用,看起来是一个列表,打印系统环境变量:
println env
新增环境变量:
env['branch'] = branch_A
使用环境变量:
env.branch
${env.branch}
定义在stage中的环境变量可以作为后续stage中的参数来使用,但前面的stage无法使用,所以环境变量一般在开始时定义
父job传递参数给子job
在job编译的时候经常会触发子job来完成特殊编译,这个时候需要触发编译子job:
build(job: 'my-jenkins-job', parameters: [string(name: 'BUILD_VERSION', value: "${env.BUILD_VERSION}")])
在my-jenkins-job这个job中就可以使用BUILD_VERSION这个参数
注意:
一般情况下我们在job中使用参数时用的env.parameter就可以直接获取该参数,但是在子job中这样使用的话就不能获取父job的环境变量,这是个坑。这个时候只能使用params.BUILD_VERSION来获取父job的环境变量
currentBuild.displayName = "${params.BUILD_VERSION}"
从其它构建工程拷贝文件
和普通Jenkins的job一样,copyArtifacts插件可以从其它job拷贝编译文件:
copyArtifacts filter: '*.zip',
fingerprintArtifacts: true,
projectName: 'job_A',
selector: lastSuccessful(),
target: 'directly'
需要注意的是,对于流水线来说,在拷贝文件的源job中需要添加一行说明,允许其它job拷贝自身文件, 比如当前job_B从job_A拷贝文件:
options {
timestamps()
copyArtifactPermission('job_B')
}
克隆仓库:
dir("${WORKSPACE}/test") {
checkout([
$class: 'GitSCM',
branches: [[name: "${env.BRANCH}"]],
userRemoteConfigs: [[credentialsId: 'Jenkins凭据配置项中的ID值', url: 'git仓库']]
])
}
options
buildDiscarder
Persist artifacts and console output for the specific number of recent Pipeline runs. For example:
options { buildDiscarder(logRotator(numToKeepStr: '1')) }
checkoutToSubdirectory
Perform the automatic source control checkout in a subdirectory of the workspace. For example:
options { checkoutToSubdirectory('foo') }
disableConcurrentBuilds
Disallow concurrent executions of the Pipeline. Can be useful for preventing simultaneous accesses to shared resources, etc. For example:
options { disableConcurrentBuilds() }
disableResume
Do not allow the pipeline to resume if the controller restarts. For example:
options { disableResume() }
newContainerPerStage
Used with docker
or dockerfile
top-level agent. When specified, each stage will run in a new container instance on the same node, rather than all stages running in the same container instance.
overrideIndexTriggers
Allows overriding default treatment of branch indexing triggers. If branch indexing triggers are disabled at the multibranch or organization label, options { overrideIndexTriggers(true) }
will enable them for this job only. Otherwise, options { overrideIndexTriggers(false) }
will disable branch indexing triggers for this job only.
preserveStashes
Preserve stashes from completed builds, for use with stage restarting. For example: options { preserveStashes() }
to preserve the stashes from the most recent completed build, or options { preserveStashes(buildCount: 5) }
to preserve the stashes from the five most recent completed builds.
quietPeriod
Set the quiet period, in seconds, for the Pipeline, overriding the global default. For example:
options { quietPeriod(30) }
retry
On failure, retry the entire Pipeline the specified number of times. For example:
options { retry(3) }
skipDefaultCheckout
Skip checking out code from source control by default in the agent
directive. For example:
options { skipDefaultCheckout() }
skipStagesAfterUnstable
Skip stages once the build status has gone to UNSTABLE. For example:
options { skipStagesAfterUnstable() }
timeout
Set a timeout period for the Pipeline run, after which Jenkins should abort the Pipeline. For example:
options { timeout(time: 1, unit: 'HOURS') }