-
Notifications
You must be signed in to change notification settings - Fork 1
/
Jenkins Groovy二三事
82 lines (75 loc) · 3.42 KB
/
Jenkins Groovy二三事
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
1、jenkins自定义邮件模板放在master的/var/lib/jenkins/email-templates下即可
其中/var/lib/jenkins是$JENKINS_HOME(用whereis jenkins可查,不要用echo $JENKINS_HOME)
2、要想在jenkins pipeline、groovy email template等groovy脚本中访问mysql数据库,需要将
mysql-connector-java-*.jar拷贝到/usr/java/packages/lib/ext/下,重启jenkins。
def dbURL = 'jdbc:mysql://10.45.59.248:3306/adminset'
def dbUserName = 'root'
def dbPassword = ''
def dbDriver = 'com.mysql.jdbc.Driver'
def db
List statis
try{
db = Sql.newInstance(dbURL,dbUserName,dbPassword,dbDriver)
statis = db.rows('SELECT center,module,passedrate,starttime,endtime FROM test_interface_statistics')
print statis
db.eachRow("select * from test_interface_statistics", { println it.id + " -- ${it.username} --"});
}catch(Exception e){
print e
}finally{
db.close()
}
3、groovy中定义一个对象(拥有多个属性)并将该对象加到一个List中,可以采用定义一个map再加到list中的方式(list of maps):
def mm = [:]
def list = []
mm = ['aaa':aaa,'bbb',bbb] //aaa,bbb是预先定义和赋值的两个变更
list << mm //将mm添加到list中
4、groovy中判断文件isFile()、isDirectory()等方法只能在jenkins master节点上运行,在slave上无法运行,只能采用findFiles、fileExists等方法
//用通配符查找文件,依次处理
def files = findFiles(glob: '**/*.postman_collection.json')
files.each{ f ->
println f.path //相对路径
println f.name //文件名
......
}
//查找文件,不支持通配符
def ff = fileExists("${dirpath}/finally.sh")
if (ff) {
sh "${dirpath}/finally*.sh"
}
5、利用邮件模板发邮件的pipeline写法:
stage("Send Email") {
steps {
script {
def mailRecipients = '[email protected],[email protected]'
def jobName = currentBuild.fullDisplayName
emailext body: '''${SCRIPT, template="test_interface2.template"}''',
mimeType: 'text/html',
subject: "[Jenkins] ${jobName}",
to: "${mailRecipients}",
replyTo: "${mailRecipients}",
recipientProviders: [[$class: 'CulpritsRecipientProvider']]
}
}
}
6、在jenkinsfile中获取scm中的其他文件,可以使用
checkout scm
7、显示适当的时间格式
import hudson.Util
println "Took ${Util.getTimeSpanString(System.currentTimeMillis() - currentBuild.startTimeInMillis)}"
8、在一个pipeline中并行执行其他job,并等待其job都执行完之后再执行下面的其他语句
stage('Build') {
steps {
script{
def jobs = ['a','b','c','d'] //a,b,c,d是job名称
def branches = [:]
jobs.each{ j ->
branches[j] = {
build job: j,parameters: [
string(name: 'param1', value:'test_param'),
string(name:'dummy', value: "${index}")]
}
}
parallel branches //并行执行并等待
}
......
}