gitlab之server端hook配置,主要有两种方式
- server端,全局配置
- server端,为指定仓库配置
本次我通过为指定仓库配置
1.进入docker容器
docker exec -it gitlab bash
2.找到目标仓库
由于 GitLab 启用了 hashed storage,仓库不再是 group/project.git 结构,而是 @hashed/<hash>.git。可以用以下命令查找某个仓库的 hash 路径
ls -l /var/opt/gitlab/git-data/repositories/@hashed/
我的实际操作, 进入到指定目录:
root@gitlab:/var/opt/gitlab/git-data/repositories/@hashed/d4/73# ls
d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35.git d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35.wiki.git
3.创建 custom_hooks 目录
cd d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35.git
mkdir -p custom_hooks
然后:
cd custom_hooks
4.创建 Hook 脚本
1>创建 pre-receive hook
vim pre-receive
写入如下内容:
#!/bin/bash
while read oldrev newrev refname; do
if [[ "$refname" == "refs/heads/main" ]]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') - Push to main branch detected: $newrev" >> /var/log/gitlab/custom_hooks.log
fi
done
内容分析:
Git 会通过 标准输入 (stdin) 传递每个推送的分支信息,格式如下:
<旧提交哈希> <新提交哈希> <引用名称>
例如:
1234567 abcdef0 refs/heads/main
然后给这个custom_hooks目录权限,如下,修改为git用户以及用户组(GitLab 作为一个托管 Git 仓库的服务,所有与 Git 操作相关的进程(如 git push 触发的服务器端钩子)都是 以 git 用户身份 运行的,而不是 root 或其他用户),同时给读写权限:
chown -R git:git /var/opt/gitlab/git-data/repositories/@hashed/d4/73/d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35.git/custom_hooks
chmod -R 775 /var/opt/gitlab/git-data/repositories/@hashed/d4/73/d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35.git/custom_hooks
2>本地推代码到仓库,编辑器日志可能会报:
remote: /var/opt/gitlab/git-data/repositories/@hashed/d4/73/d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35.git/custom_hooks/pre-receive: line 4: /var/log/gitlab/custom_hooks.log: Permission denied
error: failed to push some refs to 'ssh://gitlab.example.com:9022/front/laravel-15.git'
To ssh://gitlab.example.com:9022/front/laravel-15.git
! refs/heads/main:refs/heads/main [remote rejected] (pre-receive hook declined)
Done
分析:
pre-receive Hook 试图向 /var/log/gitlab/custom_hooks.log 写入日志,但权限不足,导致 GitLab 阻止了推送。
解决方案:
确保 custom_hooks.log 文件存在
ls -l /var/log/gitlab/custom_hooks.log
如果不存在,执行:
touch /var/log/gitlab/custom_hooks.log
赋予权限:
chown git:git /var/log/gitlab/custom_hooks.log
chmod 664 /var/log/gitlab/custom_hooks.log
3>本地再次推代码到仓库,然后打开日志可以发现如下内容
2025-03-03 15:32:48 - Push to main branch detected: 60928f4edb1fb6dc7476b5de396543e81ca92f40
说明,hook被触发
4>实际开发过程中,配置 post-receive 会比较多一些,比如我的配置,记录 推送者的用户名,可以用 $GL_USERNAME(GitLab 变量):
#!/bin/bash
while read oldrev newrev refname; do
if [[ "$refname" == "refs/heads/main" ]]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') - User: $GL_USERNAME pushed to main: $newrev" >> /var/log/gitlab/custom_hooks.log
fi
done
然后可以在日志下看到:
2025-03-03 15:47:20 - User: root pushed to main: 00d8d9ff4368e460e93c5481ac9a3f78625b5e04
