Jenkins CI Pipeline scripting
Jenkins pipeline is a suite of Jenkins plugins. Pipelines can be seen as a sequence of stages to perform the tasks just detailed, among others, thus providing continuous releases of your application.
In Jenkins, Pipelines are specified by using a specific DSL following almost the same structure as Groovy to specify its statements and expressions. Pipelines has specific sentences or elements to define script sections, which follow the Groovy syntax.
A collection of examples, tips and tricks of scripting for the Jenkins Pipeline
How to get actual working directory:
def workspace = pwd()
Function for fetch direcotry name:
def getFolderName() {
def array = pwd().split("/")
return array[array.length - 2];
}
How to edit system PATH
variable:
env.PATH = "${workspace}/env/bin:/usr/bin:${env.PATH}"
How to get git commit hash:
def commitHash = sh(returnStdout: true, script: 'git rev-parse HEAD').trim().take(7)
How to get commit message:
def commitText = sh(returnStdout: true, script: 'git show -s --format=format:"*%s* _by %an_" HEAD').trim()
How to get git commit hash from previous build:
@NonCPS
def prevBuildLastCommitId() {
def prev = currentBuild.previousBuild
def items = null
def result = null
if (prev != null && prev.changeSets != null && prev.changeSets.size() && prev.changeSets[prev.changeSets.size() - 1].items.length) {
items = prev.changeSets[prev.changeSets.size() - 1].items
result = items[items.length - 1].commitId
}
return result
}
How to get git commit hash from previous success build:
def getLastSuccessfulCommit() {
def lastSuccessfulHash = null
def lastSuccessfulBuild = currentBuild.rawBuild.getPreviousSuccessfulBuild()
if ( lastSuccessfulBuild ) {
lastSuccessfulHash = commitHashForBuild( lastSuccessfulBuild )
}
return lastSuccessfulHash
}
How to clone git repository?
def credentialsRepoId = 'GIT_ID'
def cloneRepository(def targetDir, def gitUrl, def branch) {
checkout([
$class: 'GitSCM',
branches: [[
name: '*/' + branch
]],
doGenerateSubmoduleConfigurations: false,
extensions: [[
$class: 'RelativeTargetDirectory',
relativeTargetDir: targetDir
]],
submoduleCfg: [],
userRemoteConfigs: [[
credentialsId: credentialsRepoId,
url: gitUrl
]]
])
}
How to transform JSON string to Groovy object?
def jsonParse(json) {
return new groovy.json.JsonSlurper().parseText(json)
}
// example
def json = '{"foo": "bar", "baz": "qux"}'
def data = jsonParse(json)
echo data.foo
echo data.baz
How to revers sort lists?
@NonCPS
def sortReverse(list) {
list.reverse()
}
How to get job status?
import groovy.json.JsonSlurper
def getJobStatus(String jobName){
def rx = httpRequest "https://jenkins.example.com/job/${jobName}/lastBuild/api/json"
def rxJson = new JsonSlurper().parseText(rx.getContent())
return rxJson['result']
}
How to get diff between two dates?
def timeDiff(st) {
def delta = (new Date()).getTime() - st.getTime()
def seconds = delta.intdiv(1000) % 60
def minutes = delta.intdiv(60 * 1000) % 60
return "${minutes} min ${seconds} sec"
}
// example
def start = new Date()
// another commands...
echo "Time spent: ${timeDiff(start)}"
How to check if date is in date range?
def testDate = Date.parse('yyyy-MM-dd', '2017-07-07')
def startDate = Date.parse('yyyy-MM-dd', '2017-06-03')
def endDate = Date.parse('yyyy-MM-dd', '2017-08-12')
boolean isWithinRange(Date testDate) {
return !(testDate.before(startDate) || testDate.after(endDate))
}
How to load data from csv file?
def filenames = readFile 'filenames.txt'
def filenameArray = filenames.split(",")
for(int i = 0; i < filenameArray.size(); i++) {
def file = filenameArray[i]
echo file
}
How to use docker?
node('docker') {
stage 'start database'
docker.image('redis:3.0.7-alpine').withRun { c ->
def ip = hostIp(c)
stage 'client set'
docker.image('redis:3.0.7-alpine').inside {
sh "redis-cli -h ${ip} set test 123"
}
stage 'client get'
docker.image('redis:3.0.7-alpine').inside {
sh "redis-cli -h ${ip} get test"
}
stage 'client del'
docker.image('redis:3.0.7-alpine').inside {
sh "redis-cli -h ${ip} del test"
}
}
}
def hostIp(container) {
sh "docker inspect -f {{.NetworkSettings.IPAddress}} ${container.id} > host.ip"
readFile('host.ip').trim()
}
How to list all jobs?
import jenkins.model.*
@NonCPS
def listJobs() {
Jenkins.instance.items.each {
println it.name
}
}
listJobs()
How to delete all build from job history?
def jobName = "education-webapp"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
How to load all slaves?
@NonCPS
def getSlaves() {
def slaves = []
hudson.model.Hudson.instance.slaves.each {
slaves << it.name
}
return slaves
}
for (String slave : getSlaves()) {
node(slave) {
sh "hostname"
}
}
How to load data from url?
def fetchDataFromRestApi(def url) {
def projectsApi = new URL("${url}")
return new groovy.json.JsonSlurper().parse(projectsApi.newReader())
}
How to load repository detail from Gitlab by using REST API?
@NonCPS
def getGitProjectDetails(def projectId, def gitUrl, def gitPrivateToken) {
def projectDetailsApi = new URL("${gitUrl}/projects/${projectId}?private_token=${gitPrivateToken}")
def projectDetails = new groovy.json.JsonSlurper().parse(projectDetailsApi.newReader())
def isActive = true
if( projectDetails.archived ) {
isActive = false
}
def details = new LinkedHashMap();
details.projectTags = projectDetails.tag_list
details.defaultBranch = projectDetails.default_branch
details.isActive = isActive
return details
}
// example
def projectDetails = getGitProjectDetails("project-name", "https://gitlab.com/", "supertrupersecrettoken")
echo projectDetails.projectTags
echo projectDetails.defaultBranch
echo projectDetails.isActive
Jenkins CI Pipeline scripting的更多相关文章
- DevOps实践之一:基于Docker构建企业Jenkins CI平台
基于Docker构建企业Jenkins CI平台 一.什么是CI 持续集成(Continuous integration)是一种软件开发实践,每次集成都通过自动化的构建(包括编译,发布,自动化测试)来 ...
- Jenkins CI&CD 自动化发布项目实战(下篇)
Jenkins CI&CD 自动化发布项目实战(下篇) 作者 刘畅 时间 2020-12-04 实验环境 centos7.5 主机名 ip 服务配置 软件 gitlab 172.16.1.71 ...
- Jenkins CI&CD 自动化发布项目实战(上篇)
Jenkins CI&CD 自动化发布项目实战(上篇) 作者 刘畅 时间 2020-11-28 实验环境 centos7.5 主机名 ip 服务配置 软件 gitlab 172.16.1.71 ...
- 如何在Jenkins CI 里调试
背景 厂内的CI系统把 Jenkins 和Github 连接了起来,这样Dev 只要通过github pr 就能够了解到测试job 运行的情况.有的时候,Dev会找到QA问,如何在Jenkins CI ...
- [转]利用Jenkins的Pipeline实现集群自动化部署SpringBoot项目
环境准备 Git: 安装部署使用略. Jenkins: 2.46.2版本安装部署略(修改jenkins执行用户为root,省得配置权限) JDK: 安装部署略. Maven: 安装部署略. 服务器免密 ...
- Jenkins流水线(pipeline)实战之:从部署到体验
关于Jenkins流水线(pipeline) Jenkins 流水线 (pipeline) 是一套插件,让Jenkins可以实现持续交付管道的落地和实施. 关于blueocean Blue Ocean ...
- 远程触发Jenkins的Pipeline任务
场景 虽然能配置提交代码时触发Jenkins任务,但有时并不需要每次提交代码都触发,而是仅在有需要时才执行. 除了在Jenkins页面上手动执行任务,还可以向Jenkins网站发起HTTP请求,触发指 ...
- 远程触发Jenkins的Pipeline任务的并发问题处理
前文概述 本文是<远程触发Jenkins的pipeline任务>的续篇,上一篇文章实战了如何通过Http请求远程触发指定的Jenkins任务,并且将参数传递给Jenkins任务去使用,文末 ...
- 如何在 Jenkins CI/CD 流水线中保护密钥?
CI/CD 流水线是 DevOps 团队软件交付过程的基本组成部分.该流水线利用自动化和持续监控来实现软件的无缝交付.通过持续自动化,确保 CI/CD 流水线每一步的安全性非常重要.在流水线的各个阶段 ...
随机推荐
- Redis 总结精讲 看一篇成高手系统4
本文围绕以下几点进行阐述 1.为什么使用redis2.使用redis有什么缺点3.单线程的redis为什么这么快4.redis的数据类型,以及每种数据类型的使用场景5.redis的过期策略以及内存淘汰 ...
- 20130501-Twitter向全美用户开放广告平台Twitter Ads
腾讯科技讯(晁晖)北京时间5月1日消息,据国外媒体报道,Twitter今天向所有美国用户开放了广告平台Twitter Ads.自2012年3月发布以来,Twitter Ads只向受邀请用户开放.Twi ...
- 如何理解IPD+CMMI+Scrum一体化研发管理解决方案之CMMI篇
如何快速响应市场的变化,如何推出更有竞争力的产品,如何在竞争中脱颖而出,是国内研发企业普遍面临的核心问题,为了解决这些问题,越来越多的企业开始重视创新与研发管理,加强研发过程的规范化,集成产品开发(I ...
- Factorials 阶乘(思维)
Description N 的阶乘写作N!表示小于等于N的所有正整数的乘积.阶乘会很快的变大,如13!就必须用32位整数类型来存储,70!即使用浮点数也存不下了.你的任务是 找到阶乘最后面的非零位.举 ...
- KNN算法之图像处理一
KNN: 1.数据挖掘分类技术中最简单的方法之一. 2.也称为邻近算法,K最近邻分类算法 3.每个样本都可以用它最接近的k个邻居来代表 4.一般,距离使用欧式距离或曼哈顿距离(通常,k≤20) pyt ...
- 网站UI分析
本次网站UI分析我选择的是我们石家庄铁道大学的网站,首先对于网站的分析建立在我经常使用鼠须的基础上,我可以很好的站在用户的角度来进行分析,否则对于你不熟悉的网站你可能是不能很好地体验到他的 结构. U ...
- 团队Alpha冲刺(五)
目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:翟丹丹 组员7:何家伟 组员8:政演 组员9:黄鸿杰 组员10:刘一好 组员11:何宇恒 展示 ...
- iOS- 详解如何使用ZBarSDK集成扫描二维码/条形码,点我!
1.前言 目前市场主流APP里,二维码/条形码集成主要分两种表现形式来集成: a. 一种是调用手机摄像头并打开系统照相机全屏去拍摄 b. 一种是自定义照相机视图的frame,自己控制并添加相关扫码指南 ...
- OpenLayers 3 入门教程
OpenLayers 3 入门教程摘要OpenLayers 3对OpenLayers网络地图库进行了根本的重新设计.版本2虽然被广泛使用,但从JavaScript开发的早期发展阶段开始,已日益现实出它 ...
- 1st 英文文章词频统计
英文文章词频统计: 功能:统计一篇英文文章的单词总数及出现频数并输出,之后排序,输出频数前十的单词及其频数. 实现方法:使用C语言,用fopen函数读入txt文件,fscanf函数逐个读入单词,结构体 ...