Skip to content

Instantly share code, notes, and snippets.

@yuechuanx
Created September 8, 2023 02:50
Show Gist options
  • Save yuechuanx/d6b0b335541cb75b7c6cbaccc494c5f0 to your computer and use it in GitHub Desktop.
Save yuechuanx/d6b0b335541cb75b7c6cbaccc494c5f0 to your computer and use it in GitHub Desktop.
Jenkins Pipeline Syntax Example
pipeline {
// ----------------------------------------------------------------------//
// 在任何可用代理上执行管道或阶段
agent any
// 当应用于pipeline块的顶层时,不会为整个管道运行分配全局代理,并且每个stage部分都需要包含其自己的agent部分
agent none
// 使用提供的标签在Jenkins环境中可用的代理上执行管道或阶段。不同机器可以相同 label
agent {
label 'my-defined-label'
}
// 等同 agent { label 'labelName' },但node允许其他选项(如customWorkspace)。
agent {
node {
label 'labelName'
customWorkspace '/some/other/path'
}
}
// ----------------------------------------------------------------------//
triggers {
// 周一至周五每天零点
cron('H 0 * * 1-5')
// 每天零点
cron('H 0 * * *')
// 周一至周五每隔一小时
cron('H */1 * * 1-5')
pollSCM('H */1 * * 1-5')
}
// ----------------------------------------------------------------------//
// 设置全局环境变量, 大写+下划线命名
environment {
Arstack_Version_Tag = '26fix_gun'
ARCDNN_LIB = 'ARAPP_3.1.0.1.ED_SDK28'
SUB_VERSION = '1'
}
// ----------------------------------------------------------------------//
options {
// 设置 job 超时时间, 单位: HOURS/MINUTES/SECONDS
timeout(time: 1, unit: 'HOURS')
// 所有由流水线生成的控制台输出,与该流水线发出的时间一致
timestamps()
// 失败重试次数
retry(3)
// 启动后等待时间
quietPeriod(30)
// 一旦构建状态变得UNSTABLE,跳过该阶段
skipStagesAfterUnstable()
// 为最近的流水线运行的特定数量保存组件和控制台输出
buildDiscarder(logRotator(numToKeepStr: '1'))
// 切换到子文件夹
checkoutToSubdirectory('foo')
disableResume()
// 并发始终快速失败, 即多个并发一旦存在失败将导致整个 pipeline fail
parallelsAlwaysFailFast()
// 不允许同时执行流水线。 可被用来防止同时访问共享资源等
disableConcurrentBuilds()
}
// ----------------------------------------------------------------------//
parameters {
gitParameter name: 'TAG',
type: 'PT_TAG',
defaultValue: 'auto'
string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: '')
text(name: 'DEPLOY_TEXT', defaultValue: '''One
Two
Three
''', description: '')
booleanParam(name: 'DEBUG_BUILD', defaultValue: true, description: '')
choice(name: 'CHOICES', choices: ['one', 'two', 'three'], description: '')
file(name: 'FILE', description: 'Some file to upload')
password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'A secret password')
}
// ----------------------------------------------------------------------//
stages {
stage('Pull') {
steps {
// 设置时间限制, 建议为每个 pull 与 build 等耗时时间设置
timeout(unit: 'MINUTES', time: 15, activity: true) {
// 检查特定文件或文件夹是否存在
fileExists 'ai_app'
// 切换到(相对)路径
dir(path: 'ai_app') {
// 获取 SVN 的 Repo
sh 'svn co https://viewss.artosyn.com:8443/svn/Module_Projects/AR9201_AI_APP/$Arstack_Version_Tag'
}
dir(path: 'ARCDNN') {
checkout([$class: 'GitSCM',
branches: [[name: "${params.TAG}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [],
gitTool: 'Default',
submoduleCfg: [],
userRemoteConfigs: [[url: 'git@192.168.205.214:yndong/ARCDNNLIB.git']]
])
git(url: 'git@192.168.205.214:yndong/ARCDNNLIB.git', branch: 'auto', changelog: true)
sh label: 'clone-repo', script: """
git clone git@192.168.205.214:yndong/ARCDNNLIB.git
"""
}
fileExists 'ARCDNN'
}
}
}
stage('Configuration') {
steps {
echo 'Now execute some operations'
retry(count: 5) {
sh 'echo \'do something\''
}
}
}
stage('Build') {
parallel {
stage('Build APP0') {
steps {
sh 'tree -d'
sh './demo/build.sh'
archiveArtifacts(onlyIfSuccessful: true, fingerprint: true, defaultExcludes: true, excludes: '*.ignore', artifacts: 'demo/archive/*.img')
}
}
stage('Build APP1') {
steps {
sh 'tree -d'
sh './demo/build_app_1.sh'
archiveArtifacts(onlyIfSuccessful: true, fingerprint: true, defaultExcludes: true, excludes: '*.ignore', artifacts: 'demo/archive/*.img')
}
}
stage('Build APP2') {
steps {
sh 'tree -d'
sh './demo/build_app_2.sh'
archiveArtifacts(onlyIfSuccessful: true, fingerprint: true, defaultExcludes: true, excludes: '*.ignore', artifacts: 'demo/archive/*.img')
}
}
}
}
stage('test') {
// 调用 shell, 通过检查返回值来执行不同行为, 或进行异常处理
step {
script {
def res = sh(label:"测试分支是否存在:", script: """
echo 'hello world!'
""", returnStdout: true);
if(!res.contains("hello world")){
throw new RuntimeException('提示信息')
}
}
}
// 使用异常捕获,try-catch block 或 try-catch-finally block
step {
script {
try{
someMethodMaybeThrowException()
} catch(Exception e){
// do something you want. e.g,print logs.
}
}
}
// catchError 忽略异常或可能中断构建的错误,
// 典型应用场景是针对一些后置的操作,比如构建完成发消息给构建者,保证这个消息不会因为脚本执行中断而停止。
step {
script {
//无论是否会报错,这个stage以及构建结果都不会因这个错误而失败。
catchError(buildResult: 'SUCCESS', catchInterruptions: false) {
someMethodMaybeThrowException()
}
//some post step will continued.
}
}
}
stage ('More') {
// do xxxx
steps{
script {
def tests = [:]
List=Strings.tokenize(',')
List.each { f ->
tests[f] = {
sh "echo 1; echo 2; echo ${f}"
}
}
}
}
}
stage('OTA') {
// 交互式输入
input {
message 'Should we continue?'
id 'Yes, we should.'
submitter 'alice,bob'
parameters {
string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
}
}
steps {
echo "Hello, ${PERSON}, nice to meet you."
}
} // END STAGE
stage ('create_jira_ver') {
steps{
script {
def ret = sh(script: "date '+%Y-%m-%d'", returnStdout: true) //get_date
def testVersion = [ name: '${JOB_NAME}',
archived: true,
released: true,
releaseDate: '2019-08-26',
overdue: 'true',
userReleaseDate: '6/Jul/2019',
startDate: '2019-08-26',
description: 'This is a test!!!!',
project: 'SIRSDK' ]
jiraNewVersion version: testVersion
}
}
}
} // END STAGES
// ----------------------------------------------------------------------//
post {
always {
echo 'pipeline execute finished'
}
changed {
echo 'pipeline execute status: CHANGED'
}
fixed {
echo 'pipeline execute status: FIXED'
}
regression {
echo 'pipeline execute status: REGRESSION'
}
aborted {
echo 'pipeline execute status: ABORTED'
}
failure {
echo 'pipeline execute status: FAILURE'
}
success {
echo 'pipeline execute status: SUCESS'
}
unstable {
echo 'pipeline execute status: UNSTABLE'
}
unsuccessful {
echo 'pipeline execute status: UNSUCCESSFUL'
}
cleanup {
echo 'Execute CLEAN WORKSPACE'
cleanWs()
}
} // END POST
} // END PIPELINE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment