最近又get到一个技能,通过在Jenkins pipeline中使用groovy脚本来完成一些功能。
ps: 换到了正常的team后逐渐回归正轨,和勾心斗角说声再也不见,每天都有进步,这不就是程序猿该有的样子嘛。
创建Jenkins job:
1. New Item -> 选择 'Pipeline' 填写item name,创建新的Jenkins job;
2. 进入刚才创建好的job,打开Configure,在Pipeline下填写以下内容:
Definition:Pipeline scripts from SCM
SCM: Git
Repositores:
- git url --> groovy脚本所在的git
- credentials --> 有git权限的账号和密码
- branches to build: groovy脚本所在的branch
- Repository browser:Auto
Scripts Path: groovy脚本在git中的路径
Groovy脚本:
1. 分步骤执行:
pipeline {
stages {
stage('download source') {
steps {
echo 'download source'
}
}
stage('build') {
steps {
echo 'build'
}
}
stage('deploy') {
steps {
echo 'deploy'
}
}
}
}
2. 执行shell脚本:
获取标准输出:def path = sh returnStdout: true, scripts "pwd"
只执行脚本,不需要结果: sh scripts: "pwd"
执行脚本获取状态:def status = sh returnStatus: true, scripts: "pwd"
3. 不在console中打印shell命令,比如shell命令中带了密码等敏感信息时使用:
def scriptString = "xxxxxxx"
def content = sh returnStdout: true, scripts "#!/bin/sh -e\n ${scriptString}"
4. 定义变量
- 在groovy脚本中定义变量:
properties([
parameters([
string(name:'TEST', defaultValue:'value1', description:'it's testing parameters.')
])
])
- 在Configure中定义:
勾选中This project is parameterized, 然后点击Add Parameter添加变量,选择变量类型,填写变量名称,default value,description。
- 在groovy脚本中使用变量:def param1 = params.TEST
5. 定时启动Jenkins job:
- 在groovy脚本中定义定时任务:
properties([
pipelineTriggers([cron('H 1 * * 1-5')])
])
- 在Configure中定义:
找到Build Triggers,勾选中Build periodically,在Schedule中填写cron表达式
Credentials:
1. 在Jenkins job中添加credential,打开要使用credentials的folder,在左边菜单栏中找到Credentials点进去(如果看不到Credentials说明没有权限),选择存储Credential的scope,点击Add Credentials创建
Kind:选择credential的类型,比如选择了Username and password,就是要用username+password创建一个Credential
eg:
ID: credential_test1
Username: fooUser
Password: xxxxx
ID: Credential的ID,不能和已有的Credentials一样
2. groovy脚本中使用Credential:
withCredentials([usernamePassword(credentialsId: 'credential_test1', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
// do something with credentials
def userName = "${USERNAME}"
def password = "${PASSWORD}"
}
本文介绍了如何在Jenkins Pipeline中使用Groovy脚本进行自动化任务,包括创建Jenkins job,配置Pipeline从Git获取脚本,执行不同阶段的构建任务,处理shell命令,定义和使用参数,以及安全地使用Credentials。通过实例展示了Groovy脚本在持续集成流程中的应用。
6805

被折叠的 条评论
为什么被折叠?



