博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Jenkins高级篇之Pipeline技巧篇-3-JSON文件处理多个参数进一步优化
阅读量:4302 次
发布时间:2019-05-27

本文共 5866 字,大约阅读时间需要 19 分钟。

前面一篇,我们实现了把多个构建所需的变量放在Jenkins服务器能读取的一个json文件里。这一篇,在这个基础之上,我们来进行优化和改进,并且引出新的技巧和知识点。

1.JSON文件放一个网络共享路径

有时候,我们Jenkins服务器不是人人都有权限访问的,特别是生产环境的Jenkins服务器,所以不同人使用不同json文件路径就需要有一个大家共享的文件目录,而且大家都有权限编辑和写入json文件。我想这个共享文件路径,运维人员是很容易给公司内部提供的。前面我把json文件放在了Jenkins所在机器的/tmp/anthony/test.json里。这里我把这个路径改成一个网络路径,也就是模拟实际公司中网络共享文件夹的路径。

我上面填写的路径是模仿网络共享文件的,不一定正确,而且需要运维帮你设置好一个网络路径是人人可以访问不需要输入密码的那种。

2.解释Java中三元运算符和groovy中三元运算符的简写

这里来解释下面这行代码的意思和优点。

gender = prop.GENDER? prop.GENDER.trim() : ""is_marry = prop.IS_MARRY? prop.IS_MARRY.trim() : false

上面这种写法就是Java中三元运算符的写法,prop.GENDER?表示判断这个变量是否存在,如果存在我们就prop.GENDER.trim(), 如果不存在,我们设置默认值为空字符串。这个三元运算符在开始学习if语句的时候,大家都应该学习过。上面函数trim(), 学习过java或者python都看得懂,就是去除变量值的前后的多余空格,这个写法还是很严谨,我们不可能保证用户就不一定带着多余空格进来。其实在groovy语法中,还有简写版的三元运算符:

GENDER = prop.GENDER?: "default"

上面意思还是一样,只不过是更加符合groovy的风格,意思性别字段存在吗,如果存在就是里面的值,如果不存在,就设置default这个值。这个缺点就是无法直接trim(),去除前后空格。

3.方法传参采用map格式

写到这里,我们module.groovy文件还是没有开始写代码。我们读取了Json里面的七个参数和值,只是打印出来。下面我们要换成调用方法的方式去打印出来,这里引出了map的概念,我们先写module.groovy中的一个方法。

项目文件结构和json内容

{        "NAME" : "Lucy",        "AGE" : "18",        "PHONE_NUMBER" : "13912345678",        "ADDRESS" : "Haidian Beijing",        "EMAIL" : "lucy@demo.com",        "GENDER" : "male",        "IS_MARRY" : false}

projectA-model.groovy代码如下

def getUserInfo(args) {	def name = args.name	def age = args.age	def phone = args.phone	def address = args.address	def email = args.email	def gender = args.gender	def is_marry = args.is_marry		// she or he	def binge = (gender == "male")? "he" : "she"	// if is marry	def marry = (is_marry == true)? "is marry" : "is not marry yet"	def userInfo = """	${name} come from ${address}, ${binge} is ${age} old. ${binge}'s phone number is	${phone}, or you can contact ${binge} via ${email}, ${binge} ${marry}.	"""	println userInfo}return this;

最新stage.groovy代码

import hudson.model.*;pipeline{ 		agent any	stages{		stage("Hello Pipeline") {			steps {			    script {					println "Hello Pipeline!"					println env.JOB_NAME					println env.BUILD_NUMBER				}			}		}				stage("Init paramters in json") {			steps {			    script {					println "read josn input file"					json_file = INPUT_JSON? INPUT_JSON.trim() : ""					prop = readJSON file : json_file					name = prop.NAME? prop.NAME.trim() : ""					println "Name:" + name					age = prop.AGE? prop.AGE.trim() : ""					println "Age:" + age					phone = prop.PHONE_NUMBER? prop.PHONE_NUMBER.trim() : ""					println "Phone:" + phone					address = prop.ADDRESS? prop.ADDRESS.trim() : ""					println "Address:" + address					email = prop.EMAIL? prop.EMAIL.trim() : ""					println "Email:" + email					gender = prop.GENDER? prop.GENDER.trim() : ""					println "Gender:" + gender					is_marry = prop.IS_MARRY? prop.IS_MARRY.trim() : false					println "is_marry:" + is_marry				}			}		}		stage("call a method") {			steps {			    script {					println "send the parameter as map type"					model_call = load env.WORKSPACE + "/groovy/projectA-model.groovy"					model_call.getUserInfo(name:name, age:age, phone:phone, address:address, email:email, gender:gender, is_marry:is_marry)				}			}		}	}}

测试结果

Started by user rootRebuilds build #9Rebuilds build #15Obtained src/Jenkinsfile/projectA-stages.groovy from git https://github.com/Anthonyliu86/pipeline-skills-demo.gitRunning in Durability level: MAX_SURVIVABILITY[Pipeline] Start of Pipeline[Pipeline] nodeRunning on Jenkins in /var/lib/jenkins/workspace/ProjectA-pipeline-demo[Pipeline] {[Pipeline] stage[Pipeline] { (Declarative: Checkout SCM)[Pipeline] checkoutusing credential 03214975-2168-4795-981a-ddd935f62a76 > git rev-parse --is-inside-work-tree # timeout=10Fetching changes from the remote Git repository > git config remote.origin.url https://github.com/Anthonyliu86/pipeline-skills-demo.git # timeout=10Fetching upstream changes from https://github.com/Anthonyliu86/pipeline-skills-demo.git > git --version # timeout=10using GIT_ASKPASS to set credentials  > git fetch --tags --progress https://github.com/Anthonyliu86/pipeline-skills-demo.git +refs/heads/*:refs/remotes/origin/* > git rev-parse refs/remotes/origin/master^{commit} # timeout=10 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10Checking out Revision 6f898f56636f4756ec449cf77fae1de319bb7bf9 (refs/remotes/origin/master) > git config core.sparsecheckout # timeout=10 > git checkout -f 6f898f56636f4756ec449cf77fae1de319bb7bf9Commit message: "add env.WORKSPACE" > git rev-list --no-walk 47632238361533ca98929df778da6149a4fc822d # timeout=10[Pipeline] }[Pipeline] // stage[Pipeline] withEnv[Pipeline] {[Pipeline] stage[Pipeline] { (Hello Pipeline)[Pipeline] script[Pipeline] {[Pipeline] echoHello Pipeline![Pipeline] echoProjectA-pipeline-demo[Pipeline] echo16[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] stage[Pipeline] { (Init paramters in json)[Pipeline] script[Pipeline] {[Pipeline] echoread josn input file[Pipeline] readJSON[Pipeline] echoName:Lucy[Pipeline] echoAge:18[Pipeline] echoPhone:13912345678[Pipeline] echoAddress:Haidian Beijing[Pipeline] echoEmail:lucy@demo.com[Pipeline] echoGender:male[Pipeline] echois_marry:false[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] stage[Pipeline] { (call a method)[Pipeline] script[Pipeline] {[Pipeline] echosend the parameter as map type[Pipeline] load[Pipeline] { (/var/lib/jenkins/workspace/ProjectA-pipeline-demo/groovy/projectA-model.groovy)[Pipeline] }[Pipeline] // load[Pipeline] echo	Lucy come from Haidian Beijing, he is 18 old. he's phone number is	13912345678, or you can contact he via lucy@demo.com, he is not marry yet.	[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] }[Pipeline] // withEnv[Pipeline] }[Pipeline] // node[Pipeline] End of PipelineFinished: SUCCESS

总结,上面我们写模块方法的时候参数就写了一个args, 调用方法的时候传了7个map对象进去。然后模块方法中我为什么每个变量前面都加上def, 加上之后模块中的变量都变成了局部变量。这样和已经存在内存中的stage里面的全局变量不会被覆盖和重写。

转载地址:http://mkows.baihongyu.com/

你可能感兴趣的文章
C++ 包含目录、库目录、附加依赖项总结
查看>>
c#多线程同步之EventWaitHandle使用
查看>>
一个简单的内存分配例子
查看>>
C++中关于[]静态数组和new分配的动态数组的区别分析
查看>>
MFC中将CBitmap画到cdc上
查看>>
MFC中获取任务栏大小
查看>>
MFC中OnCtlColor的用法(改变控件颜色)
查看>>
MFC与OpenCv中的图片转换实例
查看>>
mfc中主窗体显示(任务栏上方显示)
查看>>
MFC改变对话框背景图片实例
查看>>
浅谈MFC中BitBlt与StretchDIBits的区别
查看>>
关于HBITMAP,CBITMAP,BITMAP的转换以及图像显示的一点归纳
查看>>
CDC中图片绘制到控件上
查看>>
C#用到windows 消息列表Message类MSG的id代号
查看>>
C++ Map用法详解
查看>>
C++中vector作为参数的三种传参方式
查看>>
OpenCV中Mat总结
查看>>
opencv----(1) mat最好用,和IplImage,cvmat 比较
查看>>
OpenCV学习笔记之 ( 三 ) MFC显示Mat图片
查看>>
彻底解决显示Opencv中Mat图像到Mfc窗口问题
查看>>