git hooks自动部署

一、 准备

1. 笔者的git库和web服务器在同一台机器上。

# cd /data/wwwroot/html               //html目录
# git clone /home/git/html .         //首次需克隆远程库
# chown -R www.www .             //修改WEB权限为程序运行者

2. 由于hooks下的脚本一般是由git执行,所以git需要拥有相关目录的写入权限。

# usermod -a -G git www     //将git用户加入到www组

# find /data/wwwroot/html -type d -exec chmod 775 {} \;         //修改WEB根目录及以下目录权限为775 

二、 hooks脚本

# cat /home/git/html/hooks/post-receive

#!/bin/sh
unset GIT_DIR
LOG_PATH=/tmp/gitupdate.log
DeployPath=/data/wwwroot/html
cd $DeployPath
git add . -A && git stash
echo "------------Start Pull -----------" >> $LOG_PATH
echo "Time:"`date '+%Y-%m-%d %T'` >> $LOG_PATH
git pull origin master &>> $LOG_PATH
git stash pop
exit 0

 

三、 验证

1. 客户端以git身份验证上传或修改文件,首次上传文件以后发现并没有同步,通过以上打印的日志找到问题。

# cat /tmp/gitupdate.log 

------------Start Pull -----------

Time:2017-01-13 16:49:44

error: cannot open .git/FETCH_HEAD: Permission denied  

因为git账户更新文件会在.git目录下记录和创建一些文件,而我们git clone的时候使用的是root账户,修改权限:

# chown -R git.git /data/wwwroot/html/.git

2. 定时更新权限脚本

由于:

- 网站根目录下会产生新的属主为git的目录和文件,导致www不具备写入权限

- .git隐藏目录下可能会生成新的文件,导致git更新失败

- 手动干预git后部分文件权限发生变化

这些情况都可能导致自动更新出现问题,为了解决这些权限导致的失败隐患,特将更新权限写为计划任务,并根据情况决定多久执行一次,笔者定为1小时执行一次。

# crontab -l | grep chperm

0 */1 * * * /data/shell/chperm.sh

# cat /data/shell/chperm.sh 

#!/bin/bash
chown -R www.www /data/wwwroot/html
find /data/wwwroot/html -type d -exec chmod 775 {} \;
chown -R git.git /data/wwwroot/html/.git/

 

3. 改完后验证正常。

# cat /tmp/gitupdate.log

------------Start Pull -----------

Time:2017-01-13 16:53:11

From /home/git/html

 * branch            master     -> FETCH_HEAD

Updating 0591be6..1cdb27b

Fast-forward

 tests/sunleitest1.txt |    1 +

 1 files changed, 1 insertions(+), 0 deletions(-)

 create mode 100644 tests/sunleitest.txt

 create mode 100644 tests/sunleitest1.txt

 

 

 

posted @ 2017-05-20 01:20  elisun  阅读(482)  评论(0编辑  收藏  举报