Linux创建git仓库,并利用post-receive钩子实现自动部署

一、创建git仓库的用户

groupadd git

# 出于安全考虑,创建的git用户不能允许SSH登录,只能在git-shell下使用
useradd git -g git -s /usr/local/git/bin/git-shell

passwd git

二、创建仓库及设置

mkdir -p /repo/app1.git

cd /repo/app1.git

git init --bare --shared=0770

chown -R git:git /repo/app1.git

# 权限必须为7,多用户协作,组权限也应为7
chmod -R 770 /repo/app1.git

此时就可以通过以下命令克隆仓库了(密码就是前面创建git用户后设置的密码):

git clone git@192.168.1.111:/repo/app1.git

三、自动部署

cd /repo/app1.git/hooks

vim post-receive

#!/bin/sh
DIR=/xxxxxx/xxxxxx
if [ ! -d ${DIR} ];then
    mkdir -p ${DIR}
fi
source /etc/profile
sudo -u root /change_file_permission.sh ${DIR} git git
git --work-tree=${DIR} clean -df
git --work-tree=${DIR} checkout --force
sudo -u root /change_file_permission.sh ${DIR} webu webg

/xxxxxx/xxxxxx就是代码要部署的目录。


webu、webg分别为nginx或apache的运行用户及其用户组。


注意!!!每次部署时,为防止checkout失败,都会清空部署目录中未提交的文件,如果目录中有上传文件,也会被清空掉。因此需要将上传文件存放到其他目录,或者先将代码checkout到一个临时目录,然后通过rsync命令同步到部署目录(可参考另一文章:Linux下同步命令Rsync使用说明)。

chown -R git:git post-receive
chmod -R 770 post-receive

vim /change_file_permission.sh

#!/bin/sh
chown -R $2:$3 $1
chmod -R 770 $1

由于要在git用户下以root的权限运行change_file_permission.sh脚本,所以需要在root账号下添加授权:

visudo

%git ALL=(root) NOPASSWD:/change_file_permission.sh /xxxxxx/xxxxxx git git, /change_file_permission.sh /xxxxxx/xxxxxx webu webg

change_file_permission.sh通过参数可以有很宽的权限范围,所以授权时必须限定git用户只能以特定参数运行

# 只能允许root用户有此脚本的修改权限,防止git用户通过修改此脚本扩大自己的权限
chown -R root:root /change_file_permission.sh
chmod -R 700 /change_file_permission.sh
   

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值