__都非拉得的博客

Posted on 20 Nov 2018

如何使用coding.net的webhook

  1. 生成公钥

    关于coding上的公钥, 需要做一个特殊说明, 共分成两种: 一种是个人用户公钥, 另外一种是项目公钥. 先要生成一个个人公钥, 并添加到 “个人设置” -> “ssh公钥” 中去.

     ssh-keygen -t rsa -b 4096 -C "你的邮箱地址"
     # 然后一直回车就行, 当然, 设置路径的时候可以默认, 也可以自己设置一个路径
    

    然后再生成一个项目公钥, 添加到 项目中的”设置” -> “部署公钥”里面去

     sudo -Hu www ssh-keygen -t rsa # 这个地方就要注意了, 路径一定默认的, 最后的文件名一定要是id_rsa
    
  2. 准备hook文件

     # 创建和修改目录权限
     mkdir /data/www/webhook
     chown -R www.www /data/www/webhook
    
     # 创建hook文件
     sodu -Hu www touch /data/www/webhook/hook.php
     # 具体内容如下:
     <?php
     error_reporting(1);
        
     $target = '/data/www/项目'; // web目录
        
     $token = 'token';
     $wwwUser = 'www';
     $wwwGroup = 'www';
        
     $json = json_decode(file_get_contents('php://input'), true);
    
     // 因为coding的token即使是添了, 也白搭, 根本就带不过去
     //if (empty($json['token']) || $json['token'] !== $token) {
     //  header("HTTP/1.1 500 Internal Server Error");
     //	header("Status: 500 Internal Server Error");
     //	exit;
     //}
        
     $cmd = "sudo -Hu www cd $target && git pull 2>&1 && chown -R {$wwwUser}:{$wwwGroup} $target/";
        
     $result = shell_exec($cmd);
    

    然后确保你的hook文件可以访问: http://webhook.local/hook.php 在项目的”设置” -> “WebHook” 中添加上面的url, 刷新,直至出现绿色的对勾.

  3. 配置git账户

     sudo -Hu www git config --global credential.helper store # 永久保存
     sudo -Hu www git config --global user.name "名称" 
     sudo -Hu www git config --global user.email "邮箱" # 邮箱请与coding上一致
    
  4. 初始化

     sudo chown -R www:www /data/www/项目名
     # 注意此处clone必须是www用户
     sudo -Hu www git clone git@coding.net:you/repo.git /data/www/项目名/  --depth=1
    

    然后就可以测试了

  5. 利用WebHook实现PHP自动部署Git代码

    使用PHP脚本远程部署git项目