Gitlab webhook
Git&Gitlab
这段时间公司从SVN切换到Git, 本来想选择Github,无奈Github企业版价格太高,转而自己搭建了Gitlab的社区版。
Gitlab的坑
2G RAM + 1G swap;可以支持100个User。之前我搭建的时候忘记设立swap;隔一段时间Gitlab就报500 error;
解决办法参考Stackoverflow
自动化部署
- push events
- tag events
- issue events
- comment events
- comment on merge request
- comment on issue
- comment on code snippet
- merge request events
可以根据自己的需要进行监听,我们需要代码发布自动化。我选择了push events
实施方法
- 在后台建立php版本的webhook: http://www.example.com/webhook.php
- webhook.phpn内容如下
- 执行exec(‘whoami’), 查看PHP脚本的拥有者,我这里是apache
- chown -R apache:apache /web/project_directory //网站目录owner:group调整为apache
- chown -R apache:apache /var/www/.ssh //私钥的目录owner:group调整为apache
1 | //webhook.php <?php $client_token = $_SERVER['HTTP_X_GITLAB_TOKEN']; $event = $_SERVER['HTTP_X_GITLAB_EVENT']; $client_ip = $_SERVER['REMOTE_ADDR']; $access_ip = array('xxx.xxx.xxx.xxx'); //file_put_contents('gitlab-deploy.log', $client_token . "\n", FILE_APPEND); if($client_token != 'your-token'){ echo "error 403"; fwrite($fs, "Invalid token [{$client_token}]".PHP_EOL); exit(0); } // access ip if (!in_array($client_ip, $access_ip)){ echo "error 503"; fwrite($fs, "Invalid ip [{$client_ip}]".PHP_EOL); exit(0); } if($event == 'Push Hook'){ // get json data $input = file_get_contents("php://input"); $json = json_decode($input, true); //file_put_contents('gitlab-deploy.log', json_encode($_SERVER) . "\n", FILE_APPEND); if($json['project']['name'] != 'pc-dhb168'){ exit(0); } $branch = $json['ref']; switch($branch){ case 'refs/heads/stage': exec("cd /web/project/;/usr/bin/git pull origin stage 2>&1", $output, $result); break; case 'refs/heads/api': exec("cd /web/project_api/;/usr/bin/git pull origin api 2>&1", $output, $result); break; case 'refs/heads/platform': exec("cd /web/project_platform/;/usr/bin/git pull origin platform 2>&1", $output, $result); break; default: break; } } |
exec调试
1 | //查看exec的执行结果 exec("cd /web/project/;/usr/bin/git pull origin stage 2>&1", $output); var_dump($output) |