☀️ 场景:Github中代码更新后自动推送到服务器并部署
🔧 工具:Webhook
1. Github配置Webhook
📍例如我在anbydemara.github.io该仓库中存储了我的静态博客网站,我希望当我push到该仓库时,Github自动通知我的服务器并执行自定义指令。
1️⃣ 进入Github仓库,Settings->Webhooks->Add webhook

2️⃣ 填写配置信息
-
PayLoad URL:http://your_servier_ip:port/path/{id},其中port:9000,path:hooks都是默认值,我们保存不变。修改修改为自己的ip地址,并且为该Payload自定义一个id -
Content type:选择application/json格式 -
Secret:设置自己的Secret token用于验证,可以使用一个随机字符串 -
webhook触发条件:Just push event表示push代码到仓库时触发,可以自定义其他事件其他保持默认,最后
Update webhook:

2. 服务器创建hook
📍我们使用webhook工具:
webhook is a lightweight configurable tool written in Go, that allows you to easily create HTTP endpoints (hooks) on your server, which you can use to execute configured commands. You can also pass data from the HTTP request (such as headers, payload or query variables) to your commands. webhook also allows you to specify rules which have to be satisfied in order for the hook to be triggered.
2.1 安装
See:webhook/README.md at master · adnanh/webhook
我的安装目录为/usr/local/src/webhook/,安装成功后,该文件夹下有一个名为webhook的文件,我们为其添加执行权限chmod +x webhook
2.2 配置hook
1️⃣ 新建hook.json(自定义路径,这里存放在webhook安装目录下新建的my-scripts文件夹中)
该文件配置了一些规则,主要用于请求校验。在Github中我们配置了仓库push事件时,将使用webhook功能发送一个POST请求。在服务器上安装了webhook后,就可以监听对应的端口处理该请求。为了确保接受到的请求是Github触发指定事件时发送的,需进行校验:
id:需要与Github中配置PayLoad URL时指定的id一致execute-command:自定义执行脚本文件路径,请求校验成功后要执行的脚本,这里我在/usr/local/src/webhook/my-scripts新建了一个rebuildblog.sh脚本secret:需与Github中配置的一致
[
{
"id": "anburger-blog-rebuild",
"execute-command": "/usr/local/src/webhook/my-scripts/rebuildblog.sh",
"trigger-rule": {
"and": [
{
"match": {
"type": "payload-hmac-sha1",
"secret": "yoursecret",
"parameter": {
"source": "header",
"name": "X-Hub-Signature"
}
}
},
{
"match": {
"type": "value",
"value": "refs/heads/main",
"parameter": {
"source": "payload",
"name": "ref"
}
}
}
]
}
}
]
2️⃣ 新建执行脚本rebuildblog.sh(自定义路径,这里存放在webhook安装目录下新建的my-scripts文件夹中)
通过上一步hook.json校验后,将自动执行该脚本,我们可以在这里执行部署任务
#!/bin/bash
cd /root/docker/nginx/html/
# 执行你的指令,简单示例
git pull origin main # 从github拉取新代码
docker restart nginx # 重启nginx
给脚本增加执行权限chmod +x rebuildblog.sh
3️⃣ 启动webhook
# 进入webhook安装路径
cd /usr/local/src/webhook
# 启动webhook,只当hook.json,默认监听9000端口
./webhook -hooks ./my-scripts/hooks.json -verbose

测试:push代码到仓库后,成功执行脚本

到这里,我们便实现了push代码到Github,自动通知服务器并执行相应指令的基本过程。接下来设置webhook为自启动服务。
3. 设置开机自启动
1️⃣ 创建服务:
vi /etc/systemd/system/webhook.service
[Unit]
Description=Webhook Service
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/usr/local/src/webhook
ExecStart=/usr/local/src/webhook/webhook -hooks ./my-scripts/hooks.json -verbose
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target
2️⃣ 启动服务:
# 重新加载systemd
systemctl daemon-reload
# 启动服务
systemctl start webhook
# 设置开机自启动
systemctl enable webhook
# 查看服务状态
systemctl status webhook
🎉 Congratulations! 我们已经实现基本的自动化部署了,你可以尽情的在此基础上进行扩展,例如完善请求校验处理、按需求撰写你的执行脚本等。

说些什么吧!