gitlab自动化部署
查看当前web服务器的用户,我的是www
注:当前登陆用户如果和web服务器用户不是同一个用户,执行.sh脚本里的git pull时会权限不足
#切换到www用户
su www
注:如提示 This account is currently not available. 操作如下
vim /etc/passwd 将:www:x:1000:1000::/home/www:/sbin/nologin 改为:www:x:1000:1000::/home/www:/bin/bash
生成RSA
ssh-keygen #以下 会在相应的用户 /home/www/.ssh/ 文件夹下生成公私钥 Generating public/private rsa key pair. Enter file in which to save the key (/home/www/.ssh/id_rsa): /root/.ssh/id_rsa already exists. Overwrite (y/n)? y Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/www/.ssh/id_rsa. Your public key has been saved in /home/www/.ssh/id_rsa.pub. The key fingerprint is: SHA256:XAlVoeV/B+UkJCn93+RQMamGg6he8ZyWDFgPI6sw5bw root@ecs-zyl-02 The key's randomart image is: +---[RSA 2048]----+ | . . . ...
查看公钥 ids_rsa.pub 复制到gitlab
点击Add key添加
添加完成之后,需要先git pull下,密钥第一次拉取代码会有个验证
执行sell脚本需要exec函数,请解除禁用
函数
部署hook项目
<?php $valid_token = '你的token'; $client_token = $_GET['token']; $website = $_GET['website']; //多个项目的项目标识 自定义参数 $client_ip = $_SERVER['REMOTE_ADDR']; if (!in_array($website, ['api', 'admin', 'agent'])) { exit(0); } # 是否验证触发ip $array = [ '127.0.0.1', // gitlab地址 ]; if (!in_array($client_ip, $array)) { exit(1); } $fs = fopen('./' . $website .'-'. date('Y-m-d') . '.log', 'a'); fwrite($fs, 'Request on [' . date("Y-m-d H:i:s") . '] from [' . $client_ip . ']' . PHP_EOL); if ($client_token !== $valid_token) { echo "error 10001"; fwrite($fs, "Invalid token [{$client_token}]" . PHP_EOL); exit(0); } $json = file_get_contents('php://input'); $data = json_decode($json, true); fwrite($fs, '请求数据: ' . print_r($data, true) . PHP_EOL); $file = '/bin/sh /www/wwwroot/Hooks/sh/' . $website . '.sh 2>&1'; exec('whoami', $shoami); fwrite($fs, '执行人' . json_encode($shoami) . PHP_EOL); $res = exec($file, $result); fwrite($fs, '执行结果: ' . json_encode($result) . PHP_EOL . PHP_EOL); $fs and fclose($fs); #http://127.0.0.1:8036?token=你的token&website=api
gitLab设置钩子地址: