GIT 使用hooks 的post-receive 进行自动远程部署

序:一般分支开发完项目之后同步到远程要进行测试,可以使用git 自带的 hooks 可以进行远程服务器的自动部署工作。

环境:需要sshd服务的支持,如果不知道怎么配置可以看我的上一篇文章

CentOS7.4 安装git服务及配置,客户端配置 

下面我们就直接切入到如何操作 git自带的hooks 进行自动部署的工作

1、进入服务器裸仓库里面可以看到 hooks文件夹

[root@localhost test]# cd /data/git/test.git/hooks/
[root@localhost hooks]# ls -al
total 56
drwxr-xr-x 2 git  git  4096 Jan 23 10:07 .
drwxr-xr-x 7 git  git  4096 Apr  2  2018 ..
-rwxr-xr-x 1 git  git   452 Apr  2  2018 applypatch-msg.sample
-rwxr-xr-x 1 git  git   896 Apr  2  2018 commit-msg.sample
-rwxr-xr-x 1 git  git   160 Apr  2  2018 post-commit.sample
-rwxr-xr-x 1 root root  525 Jan 23 10:07 post-receive
-rwxr-xr-x 1 git  git  1060 Jan 23 09:27 post-receive.sample
-rwxr-xr-x 1 git  git   189 Apr  2  2018 post-update.sample
-rwxr-xr-x 1 git  git   398 Apr  2  2018 pre-applypatch.sample
-rwxr-xr-x 1 git  git  1578 Apr  2  2018 pre-commit.sample
-rwxr-xr-x 1 git  git  1239 Apr  2  2018 prepare-commit-msg.sample
-rwxr-xr-x 1 git  git  4951 Apr  2  2018 pre-rebase.sample
-rwxr-xr-x 1 git  git  3611 Apr  2  2018 update.sample

2、创建post-receice 文件并编辑内容

vim post-receice //填写下面的信息并保存

#!/bin/sh


#判断是不是远端仓库

IS_BARE=$(git rev-parse --is-bare-repository)
if [ -z "$IS_BARE" ]; then
echo >&2 "fatal: post-receive: IS_NOT_BARE"
exit 1
fi

unset GIT_DIR
DeployPath="/data/website/test"

echo "==============================================="
cd $DeployPath
echo "deploying the test web"

#git stash

#git pull origin master

git fetch --all
git reset --hard origin/master


time=`date`
echo "web server pull at webserver at time: $time."
echo "================================================"

3、保存完成之后需要进行rsa授权

进入git的 用户目录

cd ~

cd .ssh

创建rsa秘钥,因为服务器部署站点的用户使用的是 [email protected](可以使用git config user.email 查看)

所以生成一下对应的秘钥

ssh-keygen -t rsa -C "[email protected]"

将秘钥导入到authorized_keys文件

ssh [email protected] 'cat >> .ssh/authorized_keys' < ~/.ssh/id_rsa.pub

这样就可以实现 自动部署项目了

注:Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

给项目下的.git 权限

参考网址 权限问题

解决CentOS中使用git碰到的问题:error: cannot open .git/FETCH_HEAD: Permission denied_Allen白的博客-CSDN博客

你可能感兴趣的:(GIT,git,hooks,自动部署)