通过WebHook+Jenkins实现不同gitlab相同项目的代码同步


一、Jenkins配置

jenkins+gitlab+webhook自动触发代码构建

二、同步代码的脚本(配置在Job的Build里)

time=`date "+%Y%m%d%H%M"`
flag=0
srcgit="A套gitlab的test项目地址"
dstgit="B套gitlab的test项目地址"
branchs=${gitlabSourceBranch}					#A套gitlab传递过来的分支信息,可以在Job的环境变量信息查看,如图1
	
cd $WORKSPACE
git clone -b ${branchs}  ${srcgit} srchub
git clone -b ${branchs}  ${dstgit} dsthub || flag=1

if [ ${flag} -eq 1 ];then
    git clone -b master ${dstgit} dsthub
    cd dsthub && git checkout -b ${branchs}
fi

#保留dsthub仓库的git配置信息,否则会被srchub覆盖
cd $WORKSPACE
mv dsthub/.git .
rsync -avzHP  --delete  srchub/ dsthub/
rm -rf dsthub/.git
mv ./.git dsthub/
#rsync -avzHP --delete --exclude srchub/.git --exclude srchub/.gitignore srchub/* dsthub

cd dsthub
num1=$(git status |grep 'nothing to commit, working tree clean' | wc -l)
if [ $num1 -eq 0 ];then
  git add .
  git commit   -m "sync ${time}"
  #git checkout -b master
  git push -u origin ${branchs}
fi

图1
在这里插入图片描述

三、同步tag的脚本

srcgit="A套gitlab的test项目地址"
dstgit="B套gitlab的test项目地址"
Tag=${gitlabSourceBranch}
Tag=$(echo ${Tag##*/})
#Tag=v1.1.1

git clone  ${srcgit} srchub
git clone  ${dstgit} dsthub

#检出tag的代码
cd $WORKSPACE/srchub
git checkout -b US ${Tag}


#保留dsthub仓库的git配置信息,否则会被srchub覆盖
cd $WORKSPACE
mv dsthub/.git .
rsync -avzHP  --delete  srchub/ dsthub/
rm -rf dsthub/.git
mv ./.git dsthub/
#rsync -avzHP --delete --exclude srchub/.git --exclude srchub/.gitignore srchub/* dsthub

cd dsthub
time=`date "+%Y%m%d%H%M"`
num1=$(git status |grep 'nothing to commit, working tree clean' | wc -l)
if [ $num1 -eq 0 ];then
  git add .
  git commit -m "sync tag ${time}"
fi
git tag ${Tag}
git push origin ${Tag}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页