Gitlab Runner CI/CD中自动将代码同步到别的代码管理仓库

Gitlab & Gitlab Runner的搭建可以参考之前的文章:Gitlab相关文章


1. 前期准备

在这里插入图片描述如图所示

  1. 目标机器需要:Gitlab,作为我们的目标仓库
  2. Gitlab Runner机器除了原有的Gitlab & Gitlab Runner外,需要安装多一个Git,用于生成SSH密钥

2. SSH密钥使用

2.1 私钥

在Gitlab Runner机器中,设置一个SSH私钥的变量。这里我设置的变量名为:SSH_PRIVATE_KEY,后续在.gitlab-ci.yml文件中会使用。
在这里插入图片描述

2.2 公钥

进入到目标机器的Gitlab当中,登录后设置SSH key。
在这里插入图片描述

3. .gitlab-ci.yml

variables:
  PCF_DEPLOY_REPO: 目标机器Gitlab仓库中项目地址(eg: git@localhost:springBoot.git)
  PCF_DEPLOY_BRANCH: master
  PCF_COMMIT_USER_NAME: 生成ssh密钥时用的用户名(eg: dwayne)
  PCF_COMMIT_USER_EMAIL: 生成ssh密钥时用的邮箱地址(eg: dwayne@qq.com)

stages:
  - mergeCode

mergeCode:
  stage: mergeCode
  script:
	##
	## Run ssh-agent (inside the build environment)
	##
    - eval $(ssh-agent -s)

	##
	## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
	## We're using tr to fix line endings which makes ed25519 keys work
	## without extra base64 encoding.
	## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
	##
    - ssh-add <(echo "$SSH_PRIVATE_KEY") # 这里引入的是我们之前在CI/CD中添加的SSH私钥

	##
	## Create the SSH directory and give it the right permissions
	##
    - mkdir -p ~/.ssh
	##
	## You can optionally disable host key checking. Be aware that by adding that
	## you are susceptible to man-in-the-middle attacks.
	## WARNING: Use this only with the Docker executor, if you use it with shell
	## you will overwrite your user's SSH config.
	##
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
    # 下面的步骤不难理解,这里就不多做解释了
    - git config --global user.email "$PCF_COMMIT_USER_EMAIL"
    - git config --global user.name "$PCF_COMMIT_USER_NAME"
    - git remote remove origin || true
    - git remote remove gitlab || true
    - git remote add origin "$PCF_DEPLOY_REPO"
    - git remote add gitlab "$CI_PROJECT_URL"
    - git checkout -B $PCF_DEPLOY_BRANCH
    - git pull origin $PCF_DEPLOY_BRANCH
    - git pull gitlab $CI_COMMIT_REF_NAME
    - git push origin $PCF_DEPLOY_BRANCH
  tags:
    - xxxx # Gitlab Runner注册时,设置的tag

至此,只要我们本地提交代码,跑完CI & CD后,代码会自动同步到目标机器上了

4. 参考

官方指导文档
在GitLab CI / CD上使用SSH密钥(大佬翻译文档)

两篇文章的内容差不多

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值