使用 PHP 脚本自动部署 git 项目

git-hook

背景介绍

一般流程

在用 git 做项目版本控制的时候。一般开发者在开发环境中完成开发,会把代码 push 到代码托管平台(GitHubBitbucketCoding码云)中。在把 Git库代码 pull 到测试环境中进行项目测试,最后测试通过后的代码 pull 到生产环境中。

自动部署

但每次 push 后,都要 ssh 到服务器上。进入项目目录,再执行 git pull, 如果项目迭代频繁。每次改完代码,都要 push -> ssh -> pull 。过程还是比较繁琐。
那能不能简化这个过程呢?
答案是肯定的,这也是我写篇文章的目的。就是利用 Git hook 的功能,利用 Git hook 实现自动部署方法有很多。我在这里主要介绍何如用 PHP 脚本的方法来实现自动部署项目。测试环境自动部署和生产环境方法是一样的。

准备工作

  • 在代码托管平台创建一个私有库。(这个实例 我在 Coding 上创建的)
  • 项目服务器上安装 git (测试环境或者生产环境)

在服务器上

  • 生成公钥
    主要用于服务器和 Git 仓库的通信,在执行 git clone 或 git pull 的时候免于用户密码验证。

    ssh-keygen -t rsa -C "rockts@sina.com"
    # 最好和你代码托管平台用户一直的邮箱地址
    # 然后一直回车就行
    # 生成的文件通常是 /root/.ssh/id_rsa,如果非root用户请查看提示上的路径
    
  • 准备 hook 文件
    在 www 创建 hook 目录,在 hook 目录创建 index.php ,文件如下:

    <?php
    error_reporting(1);
    $target = './websita.com'; // 服务器上 web 目录
    $token = 'Coding  上填写的 hook 令牌';
    $wwwUser = 'www';
    $wwwGroup = 'www'; 
    
    $json = json_decode(file_get_contents('php://input'), true);
    if (empty($json['token']) || $json['token'] !== $token) {
        exit('error request');
    }            
    $cmds = array(
        "cd $target ",
        "git reset --hard origin/master && git clean -f ",
        "git pull",
        "chown -R {$wwwUser}:{$wwwGroup} $target/",
    );  
    foreach ($cmds as $cmd) {
        shell_exec($cmd);
    }
    

    如果有其他需求,比如 build、watch 都可以写这里
    $wwwUser 是服务器 web服务 运行用户 Nginx 和 Apache 都不一样,根据各自服务器自行填写。

  • 修改目录权限
     chown -R www:www /www/hook # 这里请改成你创建的hook目录
    
  • 配置 git
    git config --global user.name "rockts" 
    git config --global user.email "rockts@sina.com" # 邮箱请与conding上一致
    

备注:hock 目录的 index.php 文件,必须要确保可以访问。
http://example.com/hook/index.php 或者 http://ip/hook/index.php

在代码托管平台

  • 添加服务器用户公钥复制服务器上刚创建的的公钥到 Coding -> 账户的 ->SSH公钥 -> 新增公钥
    cat /root/.ssh/id_rsa.pub
    
  • 添加 hock在 Coding 上进入您的项目 在 设置-> WebHook 新建 hook
    • url 里输入能访问的 hook目录index.php 的地址
    • token 和 上面 index.php 文件里 $token = ‘Coding 上填写的 hook 令牌’ 一致。
    • Push 开启

    如果没有问题,稍过几秒刷新页面查看hook状态,显示为绿色勾就OK了。

部署测试

  • 先在服务器执行一次 git clone, 以后就可以实现自动部署了
    sudo -Hu www git clone git@coding.net:you/repo.git /www/websita.com/  --depth=1
    

    第一次 git clone 一定要用服务器 web 服务运行用户
    /www/websita.com/ 服务器项目目录
    git@coding.net:you/repo.git 你的 Coding 上代码库地址

  • 测试项目,给 Coding 代码库 push 一次在开发环境
    $ cd 项目目录
    $ vi test.txt
    $ git commit -am "test hook"
    $ git push
    

    过几秒后,你的服务器里项目应该有就 test.txt 就个文件了。
    大功告成!

发布者

rockts

喜欢技术,乐于开源! 乐可开源,想改变的也只有世界!

One thought on “使用 PHP 脚本自动部署 git 项目”

rockts进行回复 取消回复

电子邮件地址不会被公开。

This site uses Akismet to reduce spam. Learn how your comment data is processed.