Linux環境下GitLab配置Webhooks詳細步驟
若需自定義處理Webhook請求,需先搭建接收服務。以下以Python Flask為例:
# 創建項目目錄并進入
mkdir ~/webhook-handler && cd ~/webhook-handler
# 創建虛擬環境并激活
python3 -m venv venv
source venv/bin/activate
# 安裝Flask
pip install Flask
創建webhook_handler.py
文件,內容如下:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
# 獲取GitLab發送的JSON數據
data = request.json
print("Received webhook data:", data)
# 示例:根據事件類型執行不同操作
event_type = request.headers.get('X-Gitlab-Event')
if event_type == 'Push Hook':
print("Push event detected. Branch:", data.get('ref'))
elif event_type == 'Merge Request Hook':
print("Merge request event detected. Action:", data.get('object_attributes').get('action'))
# 返回成功響應(GitLab要求2xx狀態碼)
return jsonify({"status": "success"}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000) # 監聽所有IP的5000端口
python3 webhook_handler.py
此時服務會監聽0.0.0.0:5000/webhook
,接收POST請求并打印數據。
若接收腳本運行在本地端口(如5000),需通過Nginx/Apache將外部請求代理到該端口。以下以Nginx為例:
# Ubuntu/Debian
sudo apt update && sudo apt install nginx
# CentOS
sudo yum install nginx
編輯默認站點配置文件(如/etc/nginx/sites-available/default
),添加以下內容:
server {
listen 80;
server_name your_server_ip_or_domain; # 替換為服務器IP或域名
location /webhook {
proxy_pass http://127.0.0.1:5000; # 代理到Flask應用的5000端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
sudo nginx -t # 測試配置語法
sudo systemctl reload nginx # 重載配置
此時,外部可通過http://your_server_ip_or_domain/webhook
訪問Webhook服務。
打開瀏覽器,訪問GitLab實例,使用管理員賬號登錄,導航至目標項目頁面。
點擊左側導航欄Settings(設置)→ Webhooks(Webhooks)。
http://your_server_ip_or_domain/webhook
;若直接使用接收腳本,填http://your_server_ip:5000/webhook
);Push events
、Merge requests events
、Issue events
等,可多選);點擊Add webhook按鈕保存配置。若需測試,可點擊Test webhook按鈕(需GitLab版本支持),查看接收端是否收到請求。
若習慣命令行操作,可使用curl
調用GitLab API添加Webhook:
curl --request POST \
--form token=YOUR_GITLAB_ACCESS_TOKEN \ # 替換為GitLab個人訪問令牌(需有api權限)
--form url=WEBHOOK_RECEIVER_URL \ # 替換為Webhook接收端地址
--form enable_ssl_verification=true, # 可選:啟用SSL驗證
https://gitlab.example.com/api/v4/projects/PROJECT_ID/hooks
YOUR_GITLAB_ACCESS_TOKEN
:GitLab個人訪問令牌(生成路徑:用戶頭像→Preferences→Access Tokens);WEBHOOK_RECEIVER_URL
:Webhook接收端地址;PROJECT_ID
:項目ID(可在項目頁面URL中獲取,如https://gitlab.example.com/projects/123
中的123
)。X-Gitlab-Token
(若設置了Secret Token)驗證請求來源。例如,在Flask中添加:@app.route('/webhook', methods=['POST'])
def webhook():
secret_token = 'your_secret_token' # 與GitLab配置的Secret Token一致
received_token = request.headers.get('X-Gitlab-Token')
if received_token != secret_token:
return jsonify({"status": "invalid token"}), 403
# 處理請求...
https://
,避免數據傳輸被竊取。/var/log/nginx/access.log
);