【学习GitLab】hook

1 前言

最近在学习 GitLab,将学习成果做个简要总结,以供大家参考。如有错误,欢迎留言纠正!你的「点赞」或「打赏」将是对我最大的支持和鼓励!

本次系列文章包括:

2 GitLab hook

GitLab hook 可用于拦截特定事件(如 push 代码),以便实现功能扩展。GitLab的钩子分为两大类:

  • web hooks:事件以 http 的方式通知第三方服务,如触发持续集成。
  • custom hooks:就是 git hook 脚本文件,如 pre-receive 等。

2.1 web hooks

官方文档:https://docs.gitlab.com/ce/user/project/integrations/webhooks.html

用于将用户的所有事件以 http 的方式发送给对应的服务(一般是第三方服务),以实现功能扩展。常用于 GitLab 触发持续集成、持续部署、更新问题跟踪系统等。

GitLab 中的 web hooks有两种:

类型 作用范围
System webhooks 系统级,对所有项目有效
Project webhooks 项目级,对单个项目有效

2.2 custom hooks

官方文档:https://docs.gitlab.com/ce/administration/server_hooks.html

custom hooks 又名 server hooks,在 GitLab 12.8 之后官方将 custom hooks 更名为 server hooks。是 Git 原生 hook,包括:

  • pre-receive
  • update
  • post-receive

往GitLab服务器push提交点,会按顺序先后执行服务器上的pre-receive、update和post-receive三种类型的钩子脚本。

按作用域划分,custom hooks可细分两种:「单仓库钩子」和「全局钩子」。

2.2.1 单仓库钩子

参考:Create a server hook for a repository

按以下步骤创建单仓库钩子:

  1. 找到仓库所在目录。
  2. 在仓库 xxx.git 目录下创建 custom_hooks 子目录。
  3. 在 custom_hooks 目录中创建脚本文件(如pre-receive)。
  4. 确保脚本文件具有可执行权限,并且属主为Git用户。
  5. 编写脚本内容,脚本支持很多语言,包括但不限于shell、ruby等脚本。

举例:

ls -ls /var/opt/gitlab/git-data/repositories/@hashed/4e/07/4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce.git/custom_hooks/

4 -rwxr-xr-x+ 1 git root 308 8月  19 16:58 post-receive
4 -rwxr-xr-x+ 1 git root 307 8月  19 16:57 pre-receive
4 -rwxr-xr-x+ 1 git root 302 8月  19 16:58 update

2.2.2 全局钩子

参考:Create a global server hook for all repositories

按以下步骤创建全局钩子:

  1. 进入 /opt/gitlab/embedded/service/gitlab-shell/hooks 目录。
  2. 创建pre-receive.d, post-receive.d, or update.d 子目录。
  3. 在子目录中创建脚本文件(如pre-receive)。
  4. 确保脚本文件具有可执行权限,并且属主为Git用户。
  5. 编写脚本内容,脚本支持很多语言,包括但不限于shell、ruby等脚本。

举例:

/opt/gitlab/embedded/service/gitlab-shell/hooks/pre-receive.d/pre-receive 

2.2.3 环境变量

官网 Environment Variables 列出可以在 hook 脚本中使用 GitLab 环境变量。你可以在上面的脚本中通过 env 命令打印出所有环境变量进行查看。

猜你喜欢

转载自blog.csdn.net/benkaoya/article/details/108451293