
流水线视图可以很直观地看到每一步执行的时间和进度,方便追踪部署过程中的每一个环节。
搭建 jenkins 参考 上一篇文章
工作流
本文目的是搭建一个简单的 pipeline,当 git 仓库有提交时,builder server 进行构建和测试,完成之后 deploy server 进行部署。
本地 -> SCM: 提交代码
SCM -> Build Server: 触发 jenkins 任务
Build Server: 启动 pipeline
Build Server -> Deploy Server: 部署服务
SCM Source Code Management,如 github
Build Server jenkins 所在机器,负责构建
Deploy Server 线上服务所在机器
新建 Task
首先创建一个 Task,然后选择流水线模板


配置
Pipeline

在这里可以配置 pipeline 的脚本,definition 可以选择 Pipeline script 或 Pipeline script from SCM。
选择前者后,jenkins 脚本需要在下方填写,当任务启动后,jenkins 会执行这里配好的命令;选择后者后,任务启动后,jenkins 会去执行 SCM 仓库下配置的 script path 下的脚本。
一句话说,两者区别在于脚本是写在 jenkins 配置里,还是写在你的代码仓库里。所以修改脚本的时候在 jenkins 里配就行,方便调试,没问题之后使用 SCM 管理更好。
编写 pipeline script
以 node 服务举例,部署过程分为四步:
Build: 在 build server 上 npm install
Test: 在 build server 上进行测试
Deploy: 在 deploy server 上部署
这个脚本如下,需要将 [user] 和 [ip] 替换成 deploy server 的登录用户和 ip:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh "npm install"
}
}
stage('Test') {
steps {
sh "npm test"
}
}
stage('Deploy') {
steps {
sh """
ssh -o stricthostkeychecking=no [user]@[ip] "
source /etc/profile
cd /root/projects/my-api-server
git pull
npm install
pm2 reload wool-digger-api
"
"""
}
}
}
}
当然这是一个很粗糙的构建方式,可以稍后查看 使用 docker 进行改造。
主要概念有
agent 指示 Jenkins 分配一个执行器和工作空间来执行下面的Pipeline
stage 表示这个 Pipeline 的一个执行阶段,对应流水线中各个环节
steps 表示在这个 stage 中每一个步骤
sh 命令用来执行一条 shell 语句。 这个配置文件被执行后:
首先 jenkins 会在工作区(一般来说在 ~/.jenkins/workspace/)下拉取配置仓库指定分支的代码
pull 成功后进行 npm install(Build)
build 成功之后进行 npm test(Test)
test 成功后远程执行一段脚本,即登录 deploy server 并 cd 到服务目录,然后进行服务的更新重启操作。
npm/pm2 not found 的问题
注意上面 Deploy 中有一行 source /etc/profile,这是 login shell 和 no-login shell 的不同。
如果使用 ssh 登录再执行命令和脚本,用户会获得 login shell,shell 首先会加载 /etc/profile 文件,然后依次尝试 ~/.bash_profile、~/.bash_login 和 ~/.profile。
而如果直接使用 ssh 远程执行命令和脚本,如上面的 ssh -o,它不会去执行 /etc/profile 文件,而会去用户的 HOME 目录检查 .bashrc 并加载。所以在 /etc/profile 中设置的 path 不会生效。如果 nvm 在此文件中,那么 node、npm、pm2 等等就找不到了。
解决方法可以在 shell 脚本中先手动加载配置文件。
Build Triggers

在这里可以配置 pipeline 触发的类型
Github hook trigger fro GITScm polling
启动该项后可以通过 GitHub 的 webhook 来触发,参考 Github Plugin 文档
这里说一下最简单的配置,即手动配置。
在 Jenkins -> 系统管理 -> 系统设置中,可以找到 Git 配置,点击右边的问号按钮,可以看到默认的 jenkins hook 地址。


一般来说默认都是 $JENKINS_BASE_URL/github-webhook/。拿到这个地址后,添加到 github 的 webhook 中。

注意 这个地址是没有项目信息的,因为 github 调用这个 hook 地址时,会把仓库信息传过去,所以就只剩在 jenkins 中把 pipeline 和这个 git 仓库关联起来。这需要在 pipeline 中选择 Pipeline script from SCM 并填写 git 地址。
轮询 SCM
启动该项后,jenkins 将定时对 SCM 仓库进行轮询,当仓库有新提交时,会自动触发 pipeline。
Schedule 填写规则与 crond 类似,如 H/5 * * * * 代表每 5 分钟查询一次。详细规则可以点击右边的问号。
启动
点击 立即构建,或去仓库提交一个 commit(如果配置了 github hook),或提交一个 commit 并等待(如果配置了轮询 SCM),然后就能看到我们的第一个 pipeline 启动了!