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

导读:本篇文章讲解 Gitlab Runner CI/CD中自动将代码同步到别的代码管理仓库,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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密钥(大佬翻译文档)

两篇文章的内容差不多

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/77894.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!