Gitlab & Gitlab Runner的搭建可以参考之前的文章:Gitlab相关文章
1. 前期准备
如图所示
- 目标机器需要:Gitlab,作为我们的目标仓库
- 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密钥(大佬翻译文档)
两篇文章的内容差不多