标签 gitlab-runner 下的文章

针对 v15.3.3-jh 版本安装并配置 GitLab Runner 以实现代码同步,我将为你提供详细的步骤。该方案的核心是:在15.3.3版本上安装兼容的Runner,并通过CI/CD流水线实现代码自动同步到服务器。

第一步:安装 GitLab Runner (v15.3.3 兼容版本)
对于 GitLab 15.3.3,建议安装与之兼容的 Runner 版本(如 v15.x 系列)。

添加官方仓库并安装:

bash
# 对于 Linux x86-64 系统
curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh" | sudo bash

# 安装特定版本(例如 15.11.0,这是与 15.3 兼容的较新Runner)
sudo apt-get install gitlab-runner=15.11.0

# 对于 CentOS/RHEL
# curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh" | sudo bash
# sudo yum install gitlab-runner-15.11.0
验证安装:

bash
gitlab-runner --version
# 应显示类似:Version:      15.11.0
第二步:注册 Runner 到 GitLab 项目
注册Runner前,需要从GitLab项目获取令牌。

获取注册令牌:

进入项目页面:项目设置 → CI/CD → Runner

在 “设置Runner” 部分找到 “注册令牌”

或者在群组/实例级别获取令牌(范围更广)

执行注册命令:

bash
sudo gitlab-runner register
输入GitLab实例URL:http://你的GitLab服务器地址 或 https://...

输入获取的注册令牌

描述Runner:例如 code-sync-runner

添加标签(重要):输入 code-sync(后续CI脚本会用到)

选择执行器:推荐 shell(简单)或 docker(隔离性好)。这里以 shell 为例。

第三步:配置 Runner 以访问目标服务器
为了实现代码同步,Runner需要能免密登录到你的部署服务器。

在Runner主机生成SSH密钥:

bash
sudo -u gitlab-runner ssh-keygen -t ed25519
# 一直按回车,使用默认路径
将公钥部署到目标服务器:

bash
# 查看公钥
sudo cat /home/gitlab-runner/.ssh/id_ed25519.pub

# 将输出的内容,添加到目标服务器的 ~/.ssh/authorized_keys 文件中
测试SSH连接:

bash
sudo -u gitlab-runner ssh 目标服务器用户名@目标服务器IP "echo 连接成功"
第四步:创建 CI/CD 流水线实现自动同步
在你的GitLab仓库根目录创建 .gitlab-ci.yml 文件。

yaml
stages:
  - sync

# 定义同步到服务器的任务
sync_to_server:
  stage: sync
  tags:
    - code-sync  # 必须与注册Runner时填的标签一致
  only:
    - main  # 只在main分支推送时触发,可根据需要改为其他分支
  script:
    - echo "开始同步代码到服务器..."
    - |
      rsync -avz --delete --exclude='.git' --exclude='.gitlab-ci.yml' \
        -e "ssh -o StrictHostKeyChecking=no" \
        $CI_PROJECT_DIR/ 目标服务器用户名@目标服务器IP:/path/to/deploy/
    - echo "代码同步完成!"
  when: on_success
配置说明:

tags: 确保与注册Runner时设置的标签匹配,这样任务才会分配到你的Runner。

only: 定义触发流水线的分支。

script 中的 rsync 命令:

-avz: 归档模式,verbose,压缩传输。

--delete: 同步时删除目标目录中源目录没有的文件(保持严格一致)。

--exclude: 排除不需要同步的目录或文件。

目标服务器用户名@目标服务器IP:/path/to/deploy/: 替换为你的实际服务器路径。

第五步:测试与验证
手动触发流水线:

在GitLab项目页面,进入 CI/CD → 流水线,点击 “运行流水线”。

或直接推送代码到 main 分支。

查看执行结果:

进入流水线详情页,查看 sync_to_server 任务的日志。

确认输出中显示 代码同步完成! 且无错误。