Webhook实践 —— PHP自动部署
1、部署Gogs
2、添加git的ssh公钥
因为是用git用户部署的Gogs,接下来在服务器上配置用git账号配置ssh公钥
首先在主机上生成秘钥:
[xiaozhenkai@mysql-server ~]$ ssh-keygen -t dsa -P "" -f ~/.ssh/id_dsa Generating public/private dsa key pair. Created directory ‘/home/xiaozhenkai/.ssh‘. Your identification has been saved in /home/xiaozhenkai/.ssh/id_dsa. Your public key has been saved in /home/xiaozhenkai/.ssh/id_dsa.pub. The key fingerprint is: ec:ca:56:5d:75:5a:3a:71:e2:d7:a6:1e:1e:4d:ba:eb xiaozhenkai@mysql-server The key‘s randomart image is: +--[ DSA 1024]----+ | | | + +| | o O.| | . . = =| | S. . O | | .. . = .| | .. o + | | ... + | | .o .E. | +-----------------+
复制主机密钥
[xiaozhenkai@mysql-server .ssh]$ cat ~/.ssh/id_dsa.pub ssh-dss AAAAB3NzaC1kc3MAAACBAPc/kOGP7pIw2hwBzredF9oMnh/UQUTk9PfoWKw796/eroLUZE8ON+ibzKhgjT+/cHrqbesgku1qJ4bvSdaoJXLOgfKpZmbSWeo3ainWQx44dNxgO8ITG2Ss6oKCsUj8OBiObycP4ki6GBDLsnXu4b/bKbVE0tRbejeVpeRFP40XAAAAFQDCt3x9tEZE15jwXLvspUiur/mg9wAAAIEA0DA28/QDpnRvJ5x2t3JUBb2EkGa969kwdUHqv618S5doIKWvQhUrWLXq1/PJaZeAGGuNfMJSXtSrXBtdnES7PsoSnTfKBczTvnpyD5zD+oMr6znsPHXtkUdUPK/Zr6K2gRISTd+otNQxSuX2H7WaFwoRjyTC0ichcKpuD1acBrwAAACAY8B/Zcuo0GxAyd/WMsoUSzSUxa4WFVyFkFm9qVEXUDv91BFqhbNDDpmkxgDqH2GOCgHD4CjX1PebMBNKYSfT0LaTEKIYVn6tnvL+yoEbqt77HvID/xDxf8WIZtZ0L6BL1K8xc7tiMHbkW9dNgiFyUAnHWW+OZfU2x9t51PvsLNA= xiaozhenkai@mysql-server
登陆Gogs,用户设置——SSH秘钥——增加秘钥,然后把复制的主机密钥添加到Gogs里。
3、配置webhook
首先要有一台响应webhook的服务器,在服务器上配置
一个响应webhook的php文件,文件内容如下:
<?php //git webhook 自动部署脚本 //项目存放物理路径 $path = "your_git_path"; $requestBody = file_get_contents("php://input"); if (empty($requestBody)) { die(‘send fail‘); } $content = json_decode($requestBody, true); var_dump($content);; //若是主分支且提交数大于0 //if ($content[‘ref‘]==‘refs/heads/master‘ && $content[‘total_commits_count‘]>0) { if ($content[‘ref‘]==‘refs/heads/master‘) { $res = shell_exec("cd {$path} && git pull 2>&1");//以nginx用户运行 $res_log = ‘-------------------------‘.PHP_EOL; $res_log .= $content[‘user_name‘] . ‘ 在‘ . date(‘Y-m-d H:i:s‘) . ‘向‘ . $content[‘repository‘][‘name‘] . ‘项目的‘ . $content[‘ref‘] . ‘分支push了‘ . $content[‘total_commits_count‘] . ‘个commit:‘ . PHP_EOL; $res_log .= $res.PHP_EOL; echo $res_log; file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);//追加写入 }
注意:php函数不能禁用shell_exec,禁用后就没办法执行系统命令了。
本文出自 “ericshaw的笔记” 博客,请务必保留此出处http://xiaozhenkai.blog.51cto.com/1029756/1949841
原文地址:http://xiaozhenkai.blog.51cto.com/1029756/1949841