1. 程式人生 > >Webhook實踐 —— PHP自動部署

Webhook實踐 —— PHP自動部署

git gogs webhook

Webhook實踐 —— PHP自動部署

1、部署Gogs


參考博客:使用 Gogs 搭建自己的 Git 服務器

2、添加git的ssh公鑰


因為是用git用戶部署的Gogs,接下來在服務器上配置用git賬號配置ssh公鑰

首先在主機上生成秘鑰:

[[email protected] ~]$ 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 [email protected]
/* */ The key‘s randomart image is: +--[ DSA 1024]----+ | | | + +| | o O.| | . . = =| | S. . O | | .. . = .| | .. o + | | ... + | | .o .E. | +-----------------+


復制主機密鑰


[[email protected] .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= [email protected]
/* */


登陸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

Webhook實踐 —— PHP自動部署