「Jenkins」- 重置密码

TODO 待完善:过程并不是十分的清晰
# vi /var/lib/jenkins/config.xml file

<useSecurity>false</useSecurity>

# service jenkins restart
Manage Jenkins > Configure Global Security > Enable security -> Jenkins’ own user database
参考文献
If you forgot Jenkins Admin password how to trouble shoot? DEVOPS Interview Question Quick HOWTO: Reset Jenkins Admin Password[……]

READ MORE

「Jenkins」- 插件使用记录

问题描述
在 Jenkins Plugins 中,提供众多的插件来扩展 Jenkins 的功能,以解决在自动化过程中遇到的多种问题(或实现某些功能)。
该笔记将记录:在 Jenkins 中,完成自动化作业的方法,及常见问题的解决方案。
解决方案
隐藏“所有”视图
Editing or Replacing the All View
默认 “All” 视图为 All 类型(在创建时可以选择),而 All 类型的视图是不可以编辑,并且只能创建一个。
没有隐藏,只能删除: 1)修改默认视图:”Manage Jenkins” => “Configure System” => “Default View” 2)在修改默认视图后,可以删除原有的 “所有” 视图。
清理旧的构建
Best Strategy for Disk Space Management: Clean Up Old Builds
先升级 Jenkins 再升级插件
在插件升级前,建议先进行 Jenkins 版本升级,某些插件依赖于新版本的 Jenkins 服务,大批量的插件升级将导致 Jenkins 重启失败。
补充说明
针对 Pipeline 编程: 1)该笔记包含 Pipeline 插件的使用方法,例如,如何在 Pipeline 中使用某个插件; 2)但是 Jenkins Pipeline 本身语法编程并未包含在此(参考 Jenkins Pipeline 笔记,获取相关内容)
安装插件
在 Jenkins 与 Jenkins Pipeline 中,我们用到的的插件,及特定问题的解决方法。
使用国内镜像站点
jenkins插件清华大学镜像地址 国内
默认 Jenkins 使用 https://updates.jenkins.io/update-center.json 下载并安装扩展,但是速度较慢。
我们可以修改为使用国内镜像站点,比如清华大学镜像站点: 1)Manage Jenkins / Manage Plugins / Advanced 2)Update Site / URL https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json 3)Submit
卸载插件
uninstallation pending message 提示 Uninstallation pending 消息,表示需要重启 Jenkins 服务才能完成卸载操作。
禁用插件
Disabling plugins from CloudBees CI
通过手动进行禁用: 1)进入 /var/[……]

READ MORE

「Jenkins」- Webhook (Gitlab、Gitee)

问题描述
通过 Webhook 能够自动触发 Jenkins 构建。例如: 1)用户向 Gitlab(Gitee)提交代码,然后 Gitlab 会调用 Jenkins URL 来触发构建动作。
该笔记将记录:Webhook 相关内容,比如 自动触发构建、口令设置问题 等等,以及常见问题的解决方案。
解决方案
Secret Token
在Gitlab中配置Webhook时,需要设置口令。之后,在Gitlab通知Jenkins时,要传入口令以对身份认证。
麻烦的地方是有时候需要配置口令,有时候不需要配置口令。本文将整理何时需要配置口令,何时无需配置口令。
GitLab
Gitlab + Jenkins Multibranch Pipeline => 无需在Gitlab中配置口令 Gitlab + Jenkins Freestyle project => 需要在Gitlab中正确配置口令
# 03/19/2022 Gitlab Hook 由于依赖 ruby-runtime 插件,而 ruby-runtime 无法支持更高 JDK 版本而被废弃。 Deprecating non-Java plugins
Gitee
Gitee + Jenkins Freestyle project => 需要在Gitee中正确配置口令 Gitlab + Jenkins Multibranch Pipeline => 无需在Gitlab中配置口令
Gogs
Gogs | Jenkins plugin
Gogs 是 Gitlab 的替代品,轻量级的 Git 仓库服务。Gogs 同样支持 Webhook 功能(即在仓库发生变更时,通知 Jenkins 构建)。
1)在 Jenkins 中,安装 Gogs 插件; 2)在 Jenkins 中,配置 Gogs Webhook / Use Gogs secret 密钥; 3)在 Gogs 中,添加 Webhook 配置,地址 http(s)://<jenkins-server>/gogs-webhook/?job=<jobname> 格式,并指定密钥即可; 4)在 Gogs 中,点击 Test Delivery 测试;[……]

READ MORE

「Jenkins」- 周期性构建/定时执行作业(学习笔记,翻译)

问题描述
在 Jenkins 中,我们需要周期性构建,即定时执行作业,比如每隔 15 分钟执行构建。
通过 Build Triggers / Build periodically 实现(针对每个作业的单独设置)
该笔记将记录:Build periodically 的配置方法(实际是对帮助手册的翻译,“帮助手册”是指在 Build periodically 后的“问号按钮”)
学习笔记(文档翻译)
该字段(Build periodically)的语法与 Cron 类似,但是有轻微的不同。明确地说,每行有五个字段,使用 SPACE 或 TAB 分隔: 1)MINUTE,Minutes within the hour (0–59) 2)HOUR,The hour of the day (0–23) 3)DOM,The day of the month (1–31) 4)MONTH,The month (1–12) 5)DOW,The day of the week (0–7) where 0 and 7 are Sunday.
在单个字段上,可以指定多个值(操作符),格式如下(以下按照优先级排序): 1)*,指定多个有效值; 2)M-N,指定某个范围内的值; 3)M-N/X,*/X,在特定范围(M-N)或者全部有效值(*)内,间隔 X 的所有值; 4)A,B,…,Z,罗列出多个值;
使用 H 符号
为了平均 Jenkins 的负载,建议使用 H 符号。比如说,使用 0 0 * * * 将导致 Jenkins 在半夜集中执行定时任务,但是使用 H H * * * 将保证任务每天执行一次,但是不会集中执行。
符号 H 还支持使用范围。比如说,H H(0-7) * * * 表示在 00:00 – 07:59 内的某个时间。在符号 H 中,我们还可以使用间隔(无论是否使用范围)
可以将 H 符号视为某个范围内的随机值,但实际上它是作业名称的哈希值,而不是随机函数,因此该值对于任何给定项目均保持稳定(即对于特定作业的执行时间是固定的)
注释符号
空行或者井号(#)开始的行将被忽略。
使用别名
除此之外,还可以使用 @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly 等别名,他们依旧使用哈希值的方式进行平均均衡。比如说,@hourly 与 H * * * * 相同,表示在小时内的任意时间。@midnight 表示 12:00 AM – 2:59 AM 的某个时间。
简单示例

# 每十五分钟执行一次(可能是 :07, :22, :37, :52)
H/15 * * * *

# 在前半[……]

READ MORE

「Jenkins Pipeline」- Generic Webhook Trigger

Generic Webhook Trigger | Jenkins plugin System hooks | GitLab[……]

READ MORE

「Jenkins」- GitLab Plugin

插件介绍
此插件是一个构建触发器(Build Trigger),允许在 GitLab 中发生推送代码或创建合并请求时,触发 Jenkins 来执行构建任务。
插件站点:https://plugins.jenkins.io/gitlab-plugin
安装插件
Manage Jenkins => Manage Plugins => Available => GitLab Plugin
使用插件
该插件以作业为单位进行配置,所以以创建 Job 开始: 1)在 Jenkins 中,创建 Freestyle project 类型 Job; 2)在 Job 中,勾选 Build Triggers => Build when a change is pushed to GitLab. GitLab webhook URL: <WebHook URL>; 3)在点击 Advanced… 展开中,点击 Generate 生成 Secret token 参数; 4) 在 GitLab 的 WebHooks 中进行设置,填写 <WebHook URL> 与 Secret token 信息;
其他详细配置介绍:https://github.com/jenkinsci/gitlab-plugin
注意事项
查看 Pipline 和 Job DSL 示例:https://wiki.jenkins.io/display/JENKINS/Violation+Comments+to+GitLab+Plugin
兼容性:版本 1.2.1 插件为 Pipeline 引入了一个向后不兼容的更改。升级到此版本时,需要手动重新配置它们。Freestyle project 不会受到影响。有关详细信息,请参阅 README 文件。
变更日志查看 CHANGELOG 文件。
传入 Jenkins 的变量
在构建中,我们可以使用的变量,可以参考 Defined variables 页面。
如何获取在 WebHook 中的原始请求数据
# 07/21/2019 目前还没有获取 WebHook 原始数据的方法。倒是可以考虑 Generic Webhook Trigger Plugin 扩展。 Read json payload from gitlab webhook in Jenkins Add the ability to parse the whole webhook JSON payload How to read json payload from gitlab webhook in Jenkins #52
相关链接
Continuous In[……]

READ MORE

「Jenkins」- 当触发多个作业时,依次执行的方法

问题描述
我们的构建流程为 A 触发 B、C,当构建 B、C 结束后,再触发 D,这可以通过 Join 插件解决:
但是随着 Jenkins 的升级(在新版界面后),Join 插件已经无法正常工作。
此外 Join 插件是为 Jenkinx 1.x 开发的,从 GitHub 中来看,该插件应该必会再升级,我们需要找到它的替代品。
该笔记将记录:在 Jenkins 中,如何顺序地触发其他作业,并且还能够并行构建。
解决方案
参考文献
Shaun Abram » Blog Archive » Running Jenkins jobs sequentially[……]

READ MORE

「Jenkins Pipeline」- 发送构建结果通知

问题描述
在 Jenkins (Pipeline) 中,我们可以通过设置邮件,来通知构建结果。
但是邮件通知较慢,这是因为:邮件客户端以定时查收(轮询)的方式收取邮件;即使服务端支持 IDLE 命令,由于客户端的实现不同,也不能保证立刻收到消息。我们希望在构建结束时,“立刻”收到通知,这可以使用即时通讯工具。
该笔记将记录:在 Jenkins Pipeline 中,如何发送即时消息(IM)通知。
解决方案
方法一、使用邮件通知(Email)
虽然邮件通知较慢,但是我们依旧保留邮件通知方法,作为归档。如下为使用方法: 1)在 Manage Jenkins / Configure System / Extended E-mail Notification 中,设置邮箱帐号信息; 2)如下为在 Jenkins Pipeline 中,使用邮件通知的方法:

mail(
to: “tony@example.com,mary@example.com,tom@example.com”,
subject: “// 邮件标题”,
body: “// 邮件内容”
)

参考 Pipeline: Basic Steps / mail: Mail 文档获取详细使用方法。
方法二、通过接口通知(Web API)
很多 IM 应用(即时通讯软件),比如企业微信、钉钉、Slack,提供的 Web API 接口来发送消息。这也是我们更倾向的方法,灵活且无需担心插件更新问题。当然,这也需要我们进行简单的开发,通常仅需要使用 httpRequest 调用发送接口。
企业微信(WXWork)
方法一、通过创建应用。该方法分为以下几个步骤: 1)添加小程序 2)获取ACCESS_TOKEN凭证。参考官方「获取access_token」文档。 3)发送消息。参考官方「文本消息」文档。调用接口发送消息即可。
方法二、创建群机器人。该方法分为以下几个步骤: 1)创建群组; 2)添加群机器人; 3)调用接口发送消息;
我们使用方法二,因为更加简单,且能满足需求(但是无法推送给特定的用户)。
钉钉(DingTalk)
有着与「企业微信」相同的两种方式。
但是「添加应用」更加复杂,比如需要 IP 白名单,否则无法发送消息。也就是说,如果没有公网服务器,想要推送提醒的话,只能使用群机器人进行通知。
方法三、通过 Plugin 发送即时消息
在 Jenkins Pipeline 中,使用扩展来发送即时消息,更为简便。通过安装这些扩展,并使用其提供的 Pipeline Steps 进行消息发送操作,比调用 Web API 更加简单易用。
比如 Slac[……]

READ MORE

「Jenkins Pipeline」- 发送 IRC 消息

问题描述
我们需要使用 IRC 进行构建消息通知。因为:有很多免费 IRC 服务器;通知不涉及敏感消息;通知是即时的;我们使用 Linux 办公因此使用 钉钉、企业微信 多有不便;Slack 由于其他原因已经被占用;我们需要桌面应用,来进行消息通知提示。总之,就目前(02/14/2021)情况,IRC 是个不错的选择,我们使用 HexChat 进行消息接收与通知。
注意事项,在企业内,很少有使用 IRC 进行通讯,获取应该说“根本没有吧”。
该笔记将记录:在 Jenkins Pipeline 中,如何发送 IRC 消息,已经相关问题处理。
解决方案
插件地址:IRC | Jenkins plugin 仓库地址:jenkinsci/ircbot-plugin: Jenkins ircbot plugin

插件功能:
– 提供对构建通知和机器人的通用支持,该插件本身对用户没用,需要使用派生插件,如Jabber或IRC插件!

插件地址:
https://plugins.jenkins.io/ircbot

步骤手册:
https://jenkins.io/doc/pipeline/steps/ircbot/

其他链接:
https://github.com/jenkinsci/ircbot-plugin

第一步、安装插件
在 Manage Jenkins / Manage Plugins / Available 中,安装 IRC 扩展。
第二步、修改配置
在 Manage Jenkins / Configure System / IRC Notification 中,添加 Channel 信息,根据字段含义进行添加即可。
注意事项: 1)在修改配置之后,在一段时间内 jenkions-bot 是离线的,需要在一段时间后,才能重新进入频道; 2)如果需要向 Channel 发送消息,比如如上先进行设置,以使 JeninsBot 进入 Channel; 3)关于在 IRC 中 创建 Channel 、密码设置,参考 Channel with Password 笔记;
第三步、发送通知
在 Jenkins Pipeline 中,使用 Step 发送通知。如下程序示例:

pipeline {
agent any
stages {
stage(‘# 构建开始’) {
steps {[……]

READ MORE

「Jenkins」- 发送即时消息

内容简介
有时候电子邮件的速度还不够快,可以说非常慢了……实际上,作为一名开发人员,有时候你根本不想打开电子邮件,因为它可能会让人分心。有时候我们希望构建开始后,立即收到通知,而不是像邮件那样……
本文将介绍一些在Jenkins中发送即使消息的方法。分为两部分:(编程方式)在Jenkins Pipeline中发送消息;(非编程方式)在普通的构建任务中发送消息。
注意事项
本文后面使用“消息”一词代指“即时消息”,这里并不包含“邮件通知”等等其他的消息通知方式。
发送即时消息的两种途径
在Jenkins中,发送即时消息有两类方法:使用Jenkins插件;使用Web API接口。
# 使用插件发送
在Jenkins中,目前支持Skype、GCM Notification、IRC、Jabber这四种即时通讯工具。使用这些即时通讯工具,需要先安装「instant-messaging」插件,然后再安装对应的插件,比如「Jabber (XMPP) notifier and control」插件。当然「企业微信」与「钉钉」也有相应的插件。
这里不展开详细介绍,详细可以参考官方文档。
# 使用接口发送
使用即时通讯软件,比如企业微信、钉钉,提供的Web API接口发送消息。这也是我个人更加倾向的一种方法,灵活、不用担心插件更新问题。
普通构建方式中发送通知
# 使用插件发送
安装插件,然后在Job页面进行配置即可。
# 使用脚本调用接口
在构建的过程中,可以执行Shell脚本进行消息发送。
在流水(Pipeline)中发送通知
# 企业微信
第一种方法:添加应用。分为以下几个步骤:

添加小程序
获取ACCESS_TOKEN凭证。参考官方「获取access_token」文档。
发送消息。参考官方「文本消息」文档。调用接口发送消息即可。

第二种方法:群机器人。分为以下几个步骤:

创建群
添加群机器人
调用接口发送消息

第二种方法更加简单一些,但是无法推送给特定的用户。
# 钉钉
有着与「企业微信」相同的两种方式,但是「添加应用」更加复杂一些,需要IP白名单,否则无法发送消息。
如果没有公网服务器,想要推送提醒的话,只能使用群机器人进行通知。
# 其他几种方式
还有Skype、GCM Notification、IRC、Jabber这四种即时通讯工具,但是并不常用,所以不再展开介绍,用到再说。
参考文献
Let Jenkins Keep You Notified! (with the Instant Messaging Pl[……]

READ MORE

「Jenkins」- 发送 Jabber (XMPP) 通知

# 03/01/2021 在经过一番尝试之后,包括客户端、开源服务器,对于我们来说 XMPP 的体验没有比 IRC 高级多少,因此放弃使用 XMPP 进行消息通知。但是我们对相关资料进行记录,留作日后使用。目前,我们使用 Slack 发送构建通知。
Jabber (XMPP) notifier and control | Jenkins plugin jenkinsci/jabber-plugin: Jenkins jabber plugin Pipeline Steps reference/Jabber (XMPP) notifier and control plugin
参考文献
XMPP – Wikipedia Jabber (XMPP) notifier and control | Jenkins plugin[……]

READ MORE

「Jenkins Pipeline」- 发送 Slack 通知

问题描述
在 Jenkins Pipeline 中,当构建完成后,我们希望发送消息到 Slack Channel 进行消息通知,以告知我们构建的结果。
该笔记将记录:在 Jenkins Pipeline 中,如何使用 Slack 发送构建通知。
解决方案
第一步、准备工作
在 Slack 中,创建应用,参考 Slack/Notification Bot 笔记。
访问 https://api.slack.com/apps 页面,查看已经创建的应用。点击 <应用名称> 进入,以进行设置。
第二步、安装 Slack Notification 插件
在 Manage Jenkins / Manae Plugins / Available 中,搜索 Slack Notification 以查找 Slack Notification 扩展。
第三步、配置 Slack Notification 插件
在 Manage Jenkins / Configure System / Slack 中,填写相关信息:
1)Workspace:在创建 Slack 帐号时,使用的工作空间名称。在 https://k4nz.slack.com/admin/name 中查看,其实域名中的 k4nz 便是我们 Workspace 名称;
2)Credential:凭证信息。<Your App> / Oauth & Permissions / Bot User OAuth Token(为 xoxb-<xxxx> 格式)
3)Default channel:默认 Channel 名称。注意,如果需要该应用向 Channel 中发送消息,需要将该应用邀请到 Channel 中(比如通过 @ 方式邀请)
4)Custom slack app bot user:必须勾选,否则 Test Connection 失败。因为我们属于自定义 App,而没有使用 Slack 提供的 Jenkins CI 应用,因此需要勾选(参考 slack-plugin/README.md 说明)。
5)点击 Test Connection 测试。如果成功,则在默认 Channle 会收到一条消息,否则显示 Failure 信息;
第四步、在 Pipeline 中,向 Channel 发送消息

pipeline {
agent any
stages {
stage(‘Building’) {
steps {
slackSend channel: “#general”, color:[……]

READ MORE

「Jenkins Pipeline」- 使控制台彩色化输出(使用 AnsiColor 插件)

问题描述
在 Jenkins Pipeline 中,执行 npm 命令所产生的输出日志,包含大量 ANSI 转义序列,这些转义序列无法被解析并且会影响日志的可读性。另外有些时候,我们也希望可以在输出中显示彩色日志消息。
本文将介绍如何使用插件,使 Jenkins 的控制台能够解析 ANSI 转义序列,产生彩色化输出。
解决方法
安装 AnsiColor 插件,该插件可以解析在 Console Output 中 ANSI 转义序列输出。,在控制台中产生彩色输出。
仓库地址:jenkinsci/ansicolor-plugin: Jenkins ANSI Color Plugin
使用手册:https://jenkins.io/doc/pipeline/steps/ansicolor/
使用方法
安装及配置
安装过程与其他插件类似,这里不再赘述。
安装结束后,需要在 Manage Jenkins => Configure System => ANSI Color => Advanced… 中定义配色方案,后面要用到这个名称。
使用方法(在 Jenkins Pipeline 中)

wrap([$class: ‘AnsiColorBuildWrapper’, ‘colorMapName’: ‘xterm’]) {
sh ‘something that outputs ansi colored stuff’
}

ansiColor(‘xterm’) {
echo ‘something that outputs ansi colored stuff’
}

// 当然,你的输出中要包含ANSI转义序列才行,否则无法产生彩色输出。
// 上面代码中并未包含转义序列

上面的 xterm 既是之前配置的配色方案的名称。
附加说明
在普通作业中使用
该插件也可以在普通JOB中使用,详细可以参考「AnsiColor」插件主页。
现存问题
在 Jenkins 2.182 中,对于如下代码:

pipeline {
agent any
stages {
// 显示环境相关的信息
stage(‘example’) {
steps {
script {
ansiColor(“xterm”) {
echo “\u001B[31mPurple\u001B[0m”
stage “\u001B[31mI’m Red\u001B[0m Now not”
}
}[……]

READ MORE

「Jenkins Pipeline」- 凭证管理、使用凭证

问题描述
在 Jenkins Pipeline 中,如果直接在脚本中使用明文的敏感信息(比如密钥、证书等等),会降低程序的可移植性、安全性;
该笔记将记录:在 Jenkins 中,如何正确管理和使用凭证,以提高程序的安全性和可移植性,避免直接使用私密信息?
解决办法
安装 Credentials Binding 插件,使得我们能够使用在 Jenkins 中配置的凭证信息。
在 Shell Script 中
RefereDocker Imagesnce global credentials in Bash script in Jenkins job
1)首先,添加凭证信息,将证书注入环境变量:
2)在 Shell Script 中,使用该变量即可(与环境变量引用方法相同);
在 Jenkins Pipeline 中
参考 Pipeline Steps Reference/Credentials Binding Plugin 手册,其列举大多数凭证的使用方法与获取方法;
使用 SSH 私钥文件

withCredentials([file(credentialsId: ‘secret’, variable: ‘FILE’)]) {
sh ‘use $FILE’
}

使用以冒号分隔的帐号密码

withCredentials([usernameColonPassword(credentialsId: ‘mylogin’, variable: ‘USERPASS’)]) {
sh ”’
set +x
curl -u “$USERPASS” https://private.server/ > output
”’
}

使用字符串类型密钥

withCredentials([string(credentialsId: “CRET-ID”, variable: “varName”)]){
sh “echo $varName”
}

获取用户名密码

withCredentials([usernamePassword(credentialsId: “CRET-ID”, usernameVariable: “username”, passwordVariable: “password”)]){
sh “echo $username $password”
}

在共享库中,获取变量的方法
由 withCredentials 注入的“变量”(上述例子中的 FILE 与 USERPASS 变量),它们位于环境变量中的。
这意味着在「Jenkinsfile」与「共享库[……]

READ MORE

「Jenkins Pipeline」- 构建Docker镜像

问题描述
在Pipeline中,使用docker全局变量构建镜像动作,而不是通过Shell命令构建镜像。
通过该变量,可以进行镜像构建、测试、使用。
安装插件
在Jenkins中,需要安装相关的Pipeline插件以及「Docker Pipeline」插件。
安装过程略过……与普通插件安装过程无异。
相关链接
cloudbees/Docker Pipeline plugin Docker image for Docker Pipeline demo
# 构建镜像
# 推送镜像
# 删除镜像

stage(‘Docker Purge’) {
steps {
sh ‘docker image prune -fa’
deleteDir()
}
}

# 其他方面
「How-To Use third party libraries in Jenkins Pipeline」
参考文献
Jenkins Building Docker Image and Sending to Registry you-should-add-this-as-last-stage-or-post-task-d69fb384a361 Building your first Docker image with Jenkins 2: Guide for developer How-To Use third party libraries in Jenkins Pipeline[……]

READ MORE

「Jenkins Pipeline」- 文件、目录操作(复制、删除、重命名)

问题概述
在 Jenkins Pipeline 中,我们经常需要对文件、目录进行操作,比如移动、复制、重命名等等。
该笔记将介绍:在 Jenkins Pipeline 中,常用的目录、文件操作方法。
解决方法
第一步、安装插件
安装 File Operations Plugin 插件
创建目录

fileOperations([folderCreateOperation(‘directoryname’)])

复制文件或者目录

# 在 Jenkinsfile 中
fileOperations {
folderCopyOperation(“/path/to/src”, “/path/to/dest”)
}

# 在共享库中
fileOperations ([
folderCopyOperation(sourceFolderPath: “/path/to/src”, destinationFolderPath: “/path/to/dest”),
folderCopyOperation(sourceFolderPath: “/path/to/foo”, destinationFolderPath: “/path/to/bar”)
])

参考文献
File Operations Plugin Jenkins pipeline create directory – Stack Overflow[……]

READ MORE

「Jenkins Plugins」- Git

问题描述
该笔记将记录:在 Jenkins 中,与 Git 插件有关的内容,以及相关问题的解决方法。
解决方案
插件信息

插件功能:
该插件用于从仓库中拉取代码到工作空间中,并进行一系列动作。

插件地址:
https://plugins.jenkins.io/git

仓库链接:
https://github.com/jenkinsci/git-plugin

其他链接:
https://wiki.jenkins.io/display/JENKINS/Git+Plugin

(Push)推送代码到 GitHub 仓库
Jenkins Pipeline Git Push – Stack Overflow Is it possible to Git merge / push using Jenkins pipeline – Stack Overflow
(Pull)在 Jenkins Pipeline 中,拉取代码
What is “workspace polling” in the context of Jenkins?
使用 Git 拉取
1)安装 Git plugin 插件 2)拉取代码:

git(
url: “http://git-server/user/repository.git”,
branch: “master”,
credentialsId: “”, // 在 Jenkins 中配置的用户名和密码
changelog: true,
poll: false // Fast Remote Polling / https://plugins.jenkins.io/git
)

常见问题处理
在Job中,如何检出多个仓库
Checkout multiple git repos into same Jenkins workspace
目前(10/28/2019)Jenkins还不支持在一个Workspace中检出多个仓库,至少通过Jenkins + Git插件是不太可行的。可以考虑通过多分支流水解决该问题。
如果在「Source Code Management」的「Repositories」中设置多个「Repository URL」参数,那么Jenkins的行为有些”奇怪“。之所以这么说,是因为在工作目录中的仓库是这个样子的:

[co[……]

READ MORE

「Jenkins」- 连接 Kubernetes 集群

普通作业(Freestyle)
https://plugins.jenkins.io/kubernetes-cli https://github.com/jenkinsci/kubernetes-cli-plugin
通过 Kubernetes CLI 插件,能够实现在 Job 中与 Kubernetes Cluster 交互,但是需要单独安装 kubectl 命令;
该插件的作用是管理 kubectl 命令的凭证,操作 k8s 集群时依旧需要使用 kubectl 命令;
支持的凭证类型有: Token, as secrets (see Plain Credentials plugin) Plain KubeConfig files (see Plain Credentials plugin) Username and Password (see Credentials plugin) Certificates (see Credentials plugin) OpenShift OAuth tokens, as secrets (see Kubernetes Credentials plugin)
在 Jenkin 中添加凭证时,可以选择「secret file」类型,然后上传$HOME/.kube/config文件;
Within the Jenkins dashboard, select a Job and then select “Configure” Scroll down to the “Build Environment” section Select “Configure Kubernetes CLI (kubectl) with multiple credentials” In the “Credential” dropdown, select the credentials to authenticate on the cluster or the kubeconfig stored in Jenkins. Repeat 4 as necessary

流水线(Pipeline)
Kubernetes | Jenkins plugin
针对现有(11/23/2022)版本,在 Job 中,连接 Kubernetes 集群,依旧要使用 kubectl 命令;
withKubeConfig
传参较多,所以我们未使用该 Step 来加载配置;
withKubeCredentials
传参较多,所以我们未使用该 Step 来加载配置;
withCredentials
1)在 Jenkins Agent 中,部署 kubectl 命令(或通[……]

READ MORE

「Jenkins」- Publish Over …(学习笔记)

The goal of the Publish Over plugins is to provide a consistent set of features and behaviours when sending build artifacts … somewhere.
Publish Over plugins
Publish Over CIFS Plugin – send artifacts to a windows share Publish Over FTP Plugin – send artifacts to an FTP server Publish Over SSH Plugin – send artifacts to an SSH server (using SFTP) and/or execute commands over SSH
Overview & Configuration
Host configurations are created in the main Jenkins configuration (Manage Jenkins > Configure System). The host configurations define how to initiate connections to the remote server.
The publisher is configured in a job by selecting the checkbox next to Publish Over … (eg. Publish over FTP) (The publisher is also available as an action during a promotion if you have installed the Promoted Builds Plugin
One or more servers are selected and configured as destinations for transfer sets.
One or more transfer sets are configured to select the files to send, and where to send them.
Host configurations
创建主机配置,用于从作业配置页面中选择。
这是算是一个公共的配置,位于:Jenkins – Manage Jenkins – Configure System – Publish over XXX
要更改主机在作业配置页面下拉列表中显示的顺序,可以拖动“方形”图标,以重新排序列表。[……]

READ MORE

「Jenkins Pipeline」- SSH

问题描述
在 Jenkins Pipeline 中,需要在远程主机上执行命令。当然可以直接执行 ssh(1)命令,但是该方法可移植性较差,并非最佳实践;
该笔记将记录:在 Jenkins Pipeline 中,如何使用 SSH 命令的方法,及相关问题的解决办法;
解决方案
安装 SSH Pipeline Steps 插件: 1)插件主页:https://plugins.jenkins.io/ssh-steps/#plugin-content-sshput 2)使用文档:https://www.jenkins.io/doc/pipeline/steps/ssh-steps/ 3)项目主页:https://github.com/jenkinsci/ssh-steps-plugin#sshput
远程执行命令
然后,在 Jenkins Pipeline 中使用如下代码:

def remote = [:]
remote.name = ‘test’
remote.host = ‘test.domain.com’
remote.user = ‘root’
remote.password = ‘password’
remote.allowAnyHosts = true

sshCommand remote: remote, command: “ls -lrt”

但安全性较低:因为密码不应该直接进行编码,而是应该是创建 Credentials 后,再使用代码获取。如下示例:

// 注意,我们这里跳过了创建 Credentials 的方法

// 在 Jenkinsfile 中
withCredentials([usernamePassword(credentialsId: “Your-Credentials-Id”, usernameVariable: “username”, passwordVariable: “password”)]) {

def remote = [:]
remote.name = ‘test’
remote.host = ‘test.domain.com’
remote.user = username
remote.password = password
remote.allowAnyHosts = true

sshCommand remote: remote, command: “ls -lrt”
}

// 在共享库中有点不同
//「共享库」与「Jenkinsfile」二者是有差别的。主要在于对变量的理解上。 由 withCredentials 生成
// 的变量是位于环境中的,所以要到 env 中获取;
class Foo {

Script p[……]

READ MORE

「Jenkins Pipeline」- 集成 Selenium 测试

问题描述
我们需要在 Jenkins Pipeline 中使用 Selenium 自动化测试,该笔记将记录实现 Jenkins + Selenium 自动化测试的方法。
解决方法
我们所面对的问题,以及对应的解决方案已经在 #1 中说明,以下是我们最终的解决方案(有些无奈): 1)脱离 Jenkins 而实现自己的自动化脚本,通过退出状态反映自动化测试结果; 2)在 Jenkins Pipeline 中使用 sh 执行脚本,并获取退出状态; 3)通过自动化脚本的退出状态,判断自动化测试是否成功,并执行后续的操作及任务;
代码参考(我们只记录关键步骤):

pipeline {
agent any
stages {
stage(‘build’) {
steps {
script {
def statusCode = sh returnStatus: true, script: “groovy selenium.groovy”
if (statusCode != 0) {
// 执行失败
}
}
}
}
}
}

关于 sh 的用法可以参考 Shell Command 笔记,或者官方 Pipeline: Nodes and Processes/sh 文档。
常见问题汇总
java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;Ljava/lang/Object;)V
java – NoSuchMethodError: com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;J)V – Stack Overflow Maven Repository: org.seleniumhq.selenium » selenium-java » 3.141.59
问题描述:
在 Jenkins Pipeline 中,使用 Selenium Java 类库,在执行自动化测试程序时,返回错误:

// 程序代码
@Grab(group=’org.seleniumhq.selenium’, module=’selenium-java’, version=’3.141.59′)

WebDriver[……]

READ MORE

「Jenkins Plugins」- Token Macro

该扩展增强 Jenkins 解析表达式的能力,比如:

${GIT_REVISION,length=8} // 返回变量 GIT_REVISION 的前八位。

但是,该插件无法直接使用,需要其他插件的支持。比如在 Email Extension 中,可以从文件中读取变量:

${PROPFILE,file=”env.properties”,property=”git.committer”}

鉴于此,这里不再展开介绍,当涉及具体插件时,我们将进行详细的使用说明。
参考文献
Token Macro | Jenkins plugin[……]

READ MORE

「Jenkins Pipeline」- 在构建过程中,提示用户输入

常规用法
在某些构建过程中下,需要用户输入参数,此时可以使用 input 步骤:

pipeline {
agent any
stages {
stage(‘Example’) {
input {
message “Should we continue?”
ok “Yes, we should.”
submitter “alice,bob”
parameters {
string(name: ‘PERSON’, defaultValue: ‘Mr Jenkins’, description: ‘Who should I say hello to?’)
}
}
steps {
echo “Hello, ${PERSON}, nice to meet you.”
}
}
}
}

在 script 中
还可以在 script 语句块中使用:

pipeline {
agent any
stages {
stage(“foo”) {
steps {
script {
env.RELEASE_SCOPE = input message: ‘User input required’, ok: ‘Release!’,
parameters: [choice(name: ‘RELEASE_SCOPE’, choices: ‘patch\nminor\nmajor’, description: ‘What is the release scope?’)]
}
echo “${env.RELEASE_SCOPE}”
}
}
}
}

注意事项: 1)如果 parameters 具有单个参数,此时 input 返回为用户输入内容; 2)如果 parameters 具有多个参数,此时返回 MAP 对象,需要通过 name 取值;
注意事项
步骤 input 具有 id 参数,虽然在官方文档中说该 id 参数是可选的,但是在实际使用过程中,该参数[……]

READ MORE

「Jenkins Pipeline」- 概念术语

问题描述
该笔记将记录:在 Jenkins Pipeline 中,常见基本概念,以及相关问题的解决办法;
相关文档
内置文档
在 Jenkins 服务中,内置了一些文档,启动 Jenkins 后,即可访问查看。这包括代码生成器,全局变量的说明等等;
在官方文档中,没有列举内置环境变量,需要访问进行${YOUR_JENKINS_URL}/pipeline-syntax/globals查看;
参考文献
Jenkins/Pipeline Pipeline Syntax Getting started with Pipeline/Global Variable Reference[……]

READ MORE

「Jenkins Pipeline」- 使用 Jenkinsfile 文件(学习笔记)

问题描述
该笔记将记录:对 Jenkins/Pipeline/Using a Jenkinsfile 手册的学习整理。
解决方案
第一步、Creating a Jenkinsfile
Build Test Deploy
第二步、创建 Jenkins Pipeline 作业
创建 Pipeline 作业的过程,这里不再详细赘述;
Jenkins git submodule update fails – Stack Overflow 在 Pipeline 中,如果包含 submodule 需要检出,需要进行如下配置,以通过密码检出子模块: Additional Behaviours / Advanced sub-modules behaviours —- Recursively update submodules —- Use credentials from default remote of parent repository
Working with your Jenkinsfile
String interpolation
Using environment variables
Setting environment variables Setting environment variables dynamically
Handling credentials
For secret text, usernames and passwords, and secret files

Secret text
Usernames and passwords
Secret files

For other credential types

Combining credentials in one step

Handling parameters
Handling failure
Using multiple agents
Optional step arguments
Advanced Scripted Pipeline
Parallel execution
脚本式流水中定义环境变量:

node {
withEnv([“PATH+MAVEN=${tool ‘M3’}/bin”]) {
sh ‘mvn -B verify’
}
}

Pipeline Syntax reference
Pipeline Syntax
Pipeline Steps reference
Pipeline Steps Referenc[……]

READ MORE

「Jenkins Pipeline」- 实践经验、常见问题、代码技巧

问题描述
该笔记将记录:与 Jenkine Pipeline 有关的实践经验,以及相关问题的解决办法。
我们的自动化构建流程
开发提交代码到代码服务器(GitHub Gitlab BitBucket) 代码服务器通过 WebHook 触发 CI/CD(Codeship、Shippable、CircleCI、Jenkins) CI 服务拉去最新的代码,构建 Docker 镜像,进行测试 自动集成测试完成后,将镜像推送到私有的 Registry 运维使用最新的 Docker 镜像进行部署
加快 Jenkins Pipline 执行速度
Scaling Pipelines Project Cheetah – Faster, Leaner Pipeline That Can Keep Up With Demand
显示构建过程消耗的时间
Jenkins Pipeline: Enable timestamps in build log console – Stack Overflow

// 对于脚本式,使用 timestamps {} 包括脚本

node {
timestamps {
// do your job
}
}

// 对于声明式,使用 options 包裹时间

pipeline {
agent any
options { timestamps () }
// stages and rest of pipeline.
}

当检查特定目录发生变化后,再执行某些构建步骤
Pipeline Syntax git – How to trigger a build only if changes happen on particular set of files – Stack Overflow
通过 when 的 chagneset 能够进行判断:when { changeset “**/*.js” }

when {
anyOf {
changeset “nginx/**”
changeset “fluent-bit/**”
}
}
steps {
sh “make build-nginx”
sh “make start-nginx”
}[……]

READ MORE

「Jenkins Pipeline」- Code conversion

内容简介
本文概述我们在使用Jenkins Pipeline时的编码约定。
包名组织
/com/d3rm

/conifg
/transfer
/worker

/FileTransfer.groovy[……]

READ MORE

「Jenkins Pipeline」- 执行 resource 文件

问题描述
在 Jenkins Pipeline 中,使用 Groovy 语言进行共享库的开发。从理论上讲,我们可以按照需求,开发我们想要的任何功能。但是,现实中总会遇到一些棘手的问题。比如这次遇到的 Dependency hell – 我们在共享库中,通过 Grape 引入我们需要的模块,这些模块又依赖于其他模块,然而这些模块与 Jenkins 正在使用的模块冲突。

比如,我们需要使用 ThStock/docker-java-parser 模块解析 Dockerfile 文件,以检查其是否符合我们的规范。但是 ThStock/docker-java-parser 模块需要 commons-lang 3.5 模块,而 Jenkins 使用 commons-lang 2.6 版本。这便是冲突。

该笔记将记录:如何解决 Jenkins Pipeline 共享库的依赖问题,以及相关问题处理。
注意事项
在多数 常规的 自动化场景中,不会遇到该问题,只是我们的需求太特殊了,需要解决这个问题。
解决方案
方案一、通过脚本实现
既然存在冲突,导致部分任务我们无法通过 Pipeline 共享库实现,那么我们可以编写自定义脚本来实现(比如通过 python 脚本实现某个极度复杂的统计功能),然后在 Pipeline 中执行该脚本。
现在,我们还需要将该脚本保存到 Pipeline 共享库中,作为共享库的组件,与其他用户分享,毕竟这个脚本也是共享库的一部分。根据目前(02/20/2021)的共享库的要求,只能保存在 resources/ 目录中。现在的问题就是:我们如何执行 resources/ 目录中的脚本
在 Jenkins Pipeline 中,可以在共享库的 resources/ 目录中保存资源文件,然后通过 def text = libraryResource ‘data.yaml’ 的方式读取资源文件。
整个过程就是这样:1)通过 libraryResource 读取脚本内容,2)然后使用 writeFile 写入外部文件,2)再执行该外部文件
程序示例:

def functionsContent = libraryResource ‘com/mycorp/pipeline/somelib/functions.sh’
writeFile file: ‘/tmp/functions.sh’, text: functionsContent
sh “sh /tmp/function.sh”

方案二、计算路径(方案一的失败改进)
# 02/20/2021 一顿忙活之后,发现该方案不可行。原因是,虽然我们可以选择 Pipeline 的执行节[……]

READ MORE

「Jenkins Pipeline」- 获取自上次成功构建之后的变更

问题描述
在 Jenkins Pipeline 中,通过 currentBuild.changeSets 变量,我们可以获取仓库文件的变更记录,比如哪些代码文件发生修改,并进行某些特定操作。
比如,文件 fileA.txt 发生变更时,我们将进行某些特殊测试操作。但是,该方案存在以下场景(问题):

(1)当文件fileA.txt发生变更时,我们将进行某些操作,但是由于环境配置错误而导致构建操作失败。
(2)当我们修改环境配置后,重新触发构建(手动触发或者其他方式)。
(3)此时,由于仓库并未变更,因此已经检测不到文件fileA.txt发生变更。因为变更属于上一次构建。

这就导致特定操作无法被触发。我们需要获取这些变更,这些自上次成功构建后的变更记录。
解决方案
第一步,通过 currentBuild.previousBuild 属性,可以获取上次构建。两者为同类型对象,即方法属性是相同的; 第二步,我们只需要找到所有失败的构建,并读取其中变更记录即可;
因此依据上述步骤,代码实现如下:

def build = currentBuild
while(build != null && build.result != “SUCCESS”) {

def changeSets = build.changeSets
// doing some stuff

build = build.previousBuild
}

附加说明
在绝大多数情况下,我们遇到的问题别人早已遇到过。我们之所以没有解决是因为我们没有“搜索”到解决方案。
已知问题
通过 ChangeLogSet.Entry.getAffectedFiles() 方法,无法获取所有变更文件
问题描述: # 01/24/2021 我们共计修改 2808 个文件,通过 git diff-tree –no-commit-id –name-only -r HEAD | wc -l 验证。但是,通过 getAffectedFiles() 方法,仅获取 993 个变更文件。我们还没有找到原因,也可能是类库的 BUG。 # 01/25/2021 如果仅仅修改少量文件,比如我们测试修改 4 个文件,使用 getAffectedFiles() 是正常的。
解决方案: # 01/24/2021 我们现在没有更好的解决方案,只能通过 git diff-tree 获取被修改文件,然后再进行处理,参考 find files changed 笔记。
参考文献
How to get the changes since the last successful[……]

READ MORE

「Jenkins Pipeline」- 隐藏 Pipeline 日志

问题描述
在 Jenkins Pipeline 中,控制台(Console Output)输出的日志包含大量 Pipeline 执行日志(如下以 [Pipeline] 为前缀的日志行):


[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
The recommended git tool is: NONE
using credential GOGS-K4NZ
Fetching changes from the remote Git repository
Checking out Revision 91ff0e5ab827d5f1c9b17e47efe91d631841b060 (refs/remotes/origin/master)
Commit message: “# LZP # 2021/01/24 21:08:10”
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] timeout
Timeout set to expire in 40 min
[Pipeline] {
[Pipeline] timestamps
[Pipeline] {
[Pipeline] stage

我们希望能够隐藏这些日志,否则会影响到我们查看日志。
解决方案
方法一、使用 Simple Theme 插件
在 Manage Jenkins / Configure System / Theme 中,Add / Extra CSS,设置如下样式以隐藏:

.pipeline-new-node {
display: none;
}

方法二、使用 Log File Filter 插件(未验证)
补充说明
为什么不使用 Blue Ocean 插件?
我们的 Pipeline 比较复杂:1)对 Step 调用较多,日志冗长;2)我们还调用某些原始 Groovy 及 Java 方法,但是 Blue Ocean 插件只能显示 Step 相关的日志。因此并不适用我们的场景。
参考文献
Jenkins how to hide system level console output [JENKINS-41845] Suppress default pipeline output – Jenkins Jira djonsson/jenkins-atlassian-theme: Jenkins improve[……]

READ MORE