使用git时,传统发布方式是手动将新代码 上传到远程仓库,然后在登录服务器执行git pull命令拉取最新的代码,这种操作如果频繁更新的话,我们可以利用git的钩子来实现自动 部署 功能。
前提:
linux
php (gitpull.php)
nginx 运行用户为 www
注意网站 gitpull.php 文件权限问题,还有是否有shell_exec 命令的执行权限
一、先创建自动部署用户的密钥
sudo - www ssh-keygen -t rsa -C "syadmin@gmail.com"
二、将用户www生成的公钥添加到码云后台
cat ~/.ssh/id_rsa.pub
三、将码云域名gitee.com 添加到授权白名单
ssh-keyscan -t rsa gitee.com >> ~/.ssh/known_hosts
或者以www用户执行一次gitpull命令
sudo - www cd /data/wwwroot/www git pull
根据提示,输入 yes 即可。
四、在码云的部署钩子里进行url设置
url里填写 http://www.test.com/gitpull.php, 密码写123456
到此基本上可以实现了.
gitpull.php 脚本( 来自网友整理)
//git webhook 自动部署脚本 //项目存放物理路径,第一次clone时,必须保证该目录为空 $savePath = "/data/wwwroot/www"; $gitPath = "git@gitee.com:test/spa.git";//代码仓库 $name= "tom";//用户仓库邮箱 $email = "tom@gmail.com";//仓库用户名,一般和邮箱一致即可 $password = '123456'; $isCloned = true;//设置是否已经Clone到本地,true:已经clone,直接pull,false:先clone. //如果已经clone过,则直接拉去代码 if ($isCloned) { $requestBody = file_get_contents("php://input"); if (empty($requestBody)) { die('send fail'); } //解析Git服务器通知过来的JSON信息 $content = json_decode($requestBody, true); if($content['password'] != $password){ exit('deny'); } //若是主分支且提交数大于0 if ($content['ref'] == 'refs/heads/master' && $content['total_commits_count'] > 0) { $res = PHP_EOL . "pull start --------" . PHP_EOL; $res .= shell_exec("cd {$savePath} && git pull {$gitPath}");//拉去代码 $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:'; $res_log .= $res . PHP_EOL; $res_log .= "pull end --------" . PHP_EOL; file_put_contents("git-webhook_log.txt", $res_log, FILE_APPEND);//写入日志到log文件中 } } else { $res = "clone start --------" . PHP_EOL; //注:在这里需要设置用户邮箱和用户名,不然后面无法拉去代码 $res .= shell_exec("git config --global user.email {$email}}") . PHP_EOL; $res .= shell_exec("git config --global user.name {$name}}") . PHP_EOL; $res .= shell_exec("git clone {$gitPath} {$savePath}") . PHP_EOL; $res .= "clone end --------" . PHP_EOL; file_put_contents("git-webhook_log.txt", $res, FILE_APPEND);//写入日志到log文件中 }