Jenkins Extended choice parameter和Active Choices param 之Groovy Script使用
Groovy Script调用python脚本返回值,方法如下:
添加Extended Choice Parameter参数 pp01,逗号分隔,items数量可多不可少:
1.编写Python脚本test.py,内容如下:
#!/usr/bin/env python3
#coding=utf-8
import sys
a="aabbcc1"
mm2="%s,%s,%s"%(a,333,"cccc")
print(mm2)
python3 test.py返回结果如下,Extended choice parameter要求返回以逗号为分隔符的字符串:
aabbcc1,333,cccc
2.编写Groovy脚本,内容如下:
def retobj2 = "/usr/local/python3/bin/python3 /data/script/py/test.py".execute().text.readLines()
retobj2.each{
println it
}
========== ============================================================= ================================================================================================================
添加Active Choices Parameter参数pp03:
Active Choices接受Groovy Script返回结果为:java.util.List, an Array or a java.util.Map
小1方法:Groovy Script返回json格式结果:
python3 test4.py脚本内容如下:
#!/usr/bin/env python #coding=utf-8import json jd = {"name":"fulei.sssyang","age":"18"} #dict对象 #jj要求返回json格式 jj = json.dumps(jd) print(jj)
python3 test4.py结果返回为json格式字符串,如下:
{"name": "fulei.sssyang", "age": "18"}
Groovy脚本内容如下:
def respText = "/usr/local/python3/bin/python3 /data/script/py/test4.py".execute().text def slurper = new groovy.json.JsonSlurper() def branchs = slurper.parseText(respText) //parseText将json字符串转换为Map对象;JsonOutput类用于将Groovy对象转换为JSON字符串
//println branchs.getClass() //输出结果:class groovy.json.internal.LazyMap
return branchs
branchs打印结果为java.map对象: {name=fulei.sssyang, age=18},最终显示的为各个Value
小2方法: Groovy Script返回分行字符串
/usr/local/python3/bin/python3 /script/py/SaltAPI2.py 10.10.3.2 http://10.10.3.2:80/ADDGroup_GetGroup.ps1 zhangsan 结果返回格式为:
组1(zu1@x.com)
组2(zu2@x.com)
组3(zu3@x.com)
则Groovy脚本内容如下:
import hudson.model.User //def cuser='zhangsan' def cuser=User.current().getId() //def retobj2 = """/usr/local/python3/bin/python3 /data/script/py/test.py $cuser""".execute().text.readLines() def retobj2 = """ /usr/local/python3/bin/python3 /script/py/SaltAPI2.py 10.10.3.2 http://10.10.3.2:80/ADDGroup_GetGroup.ps1 $cuser""".execute().text.readLines() retobj2.each{ println it }
小3方法: Groovy Script返回 java.util.List 格式数据:
方法1)Groovy Script脚本内容如下:
def jlisttxt = "/usr/local/python3/bin/python3 /data/script/py/test5.py".execute().text def jlist = new groovy.json.JsonSlurper().parseText(jlisttxt) def jj=jlist['list'] return jj
jj输出结果为java.util.ArrayList对象:[a, b, c1]
test5.py脚本内容:
#!/usr/bin/env python #coding=utf-8 import sys,json mmlist={"list":["a","b","c1"]} listj = json.dumps(mmlist) print(listj)
python3 test5.py输出结果:
['a2', 'b2', 'c2']
==================================================
方法2)
test6.py内容:
#!/usr/bin/env python #coding=utf-8 mm3=['a2','b2','c2'] print(mm3)
python3 test6.py输出结果:['a2', 'b2', 'c2']
Groovy Script内容如下:
def ids = "/usr/local/python3/bin/python3 /data/script/py/test6.py".execute().text def idList = Eval.me(ids) //格式为ArrayList return idList
println idList结果:[a2, b2, c2],此为class java.util.ArrayList对象