从安装到CI/CD流水线:用GitLab Runner在本地Ubuntu上打造自动化测试部署环境
从安装到CI/CD流水线:用GitLab Runner在本地Ubuntu上打造自动化测试部署环境
在当今快节奏的软件开发环境中,自动化已经成为提升团队效率的关键。对于已经使用Git进行版本控制的中小型团队来说,如何将代码管理、测试验证和部署发布无缝衔接,构建一套完整的开发运维流水线,是向高效协作迈出的重要一步。本文将带你从零开始,在Ubuntu服务器上搭建GitLab CE环境,并配置GitLab Runner实现Shell执行器的自动化流程,最终形成代码提交即触发测试、部署的完整闭环。
这套方案特别适合10人以下的开发团队,或需要严格控制代码质量的中小型项目。我们将避开复杂的容器化部署,采用最直接的Shell执行器方案,让你在30分钟内建立起可立即投入使用的CI/CD基础架构。不同于简单的GitLab安装教程,本文重点在于如何将各个组件有机整合,打造真正可落地的自动化工作流。
1. 环境准备与GitLab CE安装
在开始构建CI/CD流水线之前,我们需要先搭建好基础环境。Ubuntu Server 22.04 LTS是目前最稳定的长期支持版本,推荐作为生产环境的基础操作系统。
1.1 系统基础配置
首先确保系统已更新到最新状态:
sudo apt update && sudo apt upgrade -y安装必要的依赖包:
sudo apt install -y curl openssh-server ca-certificates postfix对于邮件服务,如果只是内部测试使用,可以选择"Local only"安装选项。如需对外发送通知邮件,则需要正确配置SMTP服务。
1.2 GitLab CE安装与优化
GitLab官方提供了便捷的安装脚本,执行以下命令添加仓库:
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash接着安装GitLab CE最新稳定版:
sudo apt install gitlab-ce安装完成后,我们需要对默认配置进行优化调整,特别是对于资源有限的服务器。编辑配置文件:
sudo vim /etc/gitlab/gitlab.rb关键优化参数包括:
| 配置项 | 推荐值 | 说明 |
|---|---|---|
puma['worker_processes'] | 0 | 禁用集群模式减少内存占用 |
sidekiq['concurrency'] | 2 | 降低后台任务并发数 |
postgresql['shared_buffers'] | 64MB | 减少数据库缓存大小 |
prometheus_monitoring['enable'] | false | 禁用监控节省资源 |
应用配置更改:
sudo gitlab-ctl reconfigure提示:首次配置完成后,root用户的初始密码存储在
/etc/gitlab/initial_root_password,登录后请立即修改。
2. GitLab Runner的配置与管理
GitLab Runner是CI/CD流水线的执行引擎,它负责运行我们定义的自动化任务。与常见的Docker执行器不同,Shell执行器更适合资源有限的环境,且能与主机系统直接交互。
2.1 Runner安装与注册
添加官方仓库并安装Runner:
curl -sS https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash sudo apt install gitlab-runner注册Runner到GitLab实例:
sudo gitlab-runner register注册过程中需要提供:
- GitLab实例URL(如http://your-server-ip)
- 注册令牌(从GitLab Admin Area > Runners页面获取)
- 描述标签(如"ubuntu-shell-runner")
- 执行器类型(选择"shell")
2.2 Shell执行器安全配置
使用Shell执行器需要特别注意安全性,因为任务将以gitlab-runner用户身份直接操作系统。建议采取以下措施:
- 限制gitlab-runner用户的权限:
sudo usermod -s /bin/bash gitlab-runner sudo mkdir /home/gitlab-runner sudo chown gitlab-runner:gitlab-runner /home/gitlab-runner- 配置sudo权限(谨慎使用):
echo "gitlab-runner ALL=(ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/gitlab-runner- 设置构建目录:
sudo mkdir /builds sudo chown gitlab-runner:gitlab-runner /builds在/etc/gitlab-runner/config.toml中配置构建目录:
[[runners]] name = "primary-shell-runner" builds_dir = "/builds" [runners.custom_build_dir] [runners.cache] [runners.cache.s3] [runners.cache.gcs]2.3 Runner维护与监控
日常维护命令:
- 启动服务:
sudo gitlab-runner start - 停止服务:
sudo gitlab-runner stop - 查看状态:
sudo gitlab-runner status - 重启服务:
sudo gitlab-runner restart
可以通过系统日志监控Runner运行情况:
journalctl -u gitlab-runner -f3. 构建自动化测试流水线
一个完整的CI/CD流程通常从自动化测试开始。我们将创建一个三阶段的流水线:构建→测试→部署,确保只有通过测试的代码才能进入部署阶段。
3.1 .gitlab-ci.yml基础配置
在项目根目录创建.gitlab-ci.yml文件,定义基本的流水线结构:
stages: - build - test - deploy variables: PROJECT_NAME: "my-awesome-project" before_script: - echo "Starting pipeline for ${PROJECT_NAME}" - export LC_ALL=C.UTF-83.2 测试阶段实现
以Python项目为例,添加测试阶段配置:
unit_tests: stage: test script: - pip install -r requirements.txt - pytest tests/unit --cov=src --cov-report=xml artifacts: paths: - coverage.xml reports: cobertura: coverage.xml only: - merge_requests - master关键配置说明:
artifacts:保存测试生成的报告文件reports:将覆盖率报告集成到GitLab界面only:限制只在合并请求和master分支运行
3.3 质量门禁设置
结合测试覆盖率设置质量门禁,在项目Settings > CI/CD > General pipelines中添加规则:
test: coverage: '/^TOTAL.*\s+(\d+)%$/'同时可以在.gitlab-ci.yml中设置允许失败的测试任务:
integration_tests: stage: test script: - ./run_integration_tests.sh allow_failure: true4. 自动化部署策略实现
部署阶段需要根据不同的分支采取不同的策略。我们将实现开发环境、预发布环境和生产环境的三级部署体系。
4.1 多环境部署配置
定义部署任务时使用environment关键字:
deploy_to_dev: stage: deploy script: - scp -r ./dist/* dev-user@dev-server:/var/www/html environment: name: development url: https://dev.example.com only: - develop deploy_to_staging: stage: deploy script: - ansible-playbook -i staging deploy.yml environment: name: staging url: https://staging.example.com only: - master deploy_to_prod: stage: deploy script: - ansible-playbook -i production deploy.yml environment: name: production url: https://example.com when: manual only: - tags4.2 保护分支与部署权限
在GitLab项目设置中,配置分支保护规则:
- 进入Settings > Repository > Protected Branches
- 对master分支设置:
- Allowed to merge: Maintainers
- Allowed to push: No one
- 对production分支设置:
- Allowed to merge: No one
- Allowed to push: No one
这样确保了只有通过合并请求且经过审核的代码才能进入生产环境。
4.3 回滚机制实现
在.gitlab-ci.yml中添加回滚任务:
rollback_prod: stage: deploy script: - git checkout ${CI_COMMIT_SHA} - ansible-playbook -i production rollback.yml environment: name: production action: stop when: manual only: - master配合Ansible playbook实现一键回滚:
- hosts: prod_web tasks: - name: Restore previous version command: /opt/scripts/restore_backup.sh {{ lookup('env', 'CI_PIPELINE_ID') }}5. 高级技巧与疑难排查
在实际使用中,你可能会遇到各种特殊情况。以下是几个常见问题的解决方案。
5.1 Runner任务超时处理
默认情况下,Runner任务会在1小时后超时。对于长时间运行的任务,可以在.gitlab-ci.yml中调整:
job_with_timeout: script: ./long_running_script.sh timeout: 2 hours或者在Runner的config.toml中全局设置:
[[runners]] executor = "shell" [runners.custom_build_dir] [runners.cache] [runners.shell] job_timeout = 72005.2 缓存依赖加速构建
合理使用缓存可以显著减少重复安装依赖的时间:
cache: key: ${CI_COMMIT_REF_SLUG} paths: - venv/ - .cache/pip - node_modules/ install_deps: stage: build script: - python -m pip install --user -r requirements.txt cache: policy: pull-push5.3 多Runner负载均衡
当项目规模扩大时,可以注册多个Runner并在config.toml中配置限制:
[[runners]] name = "runner-1" limit = 2 [runners.custom_build_dir] [runners.cache] [[runners]] name = "runner-2" limit = 2 [runners.custom_build_dir] [runners.cache]然后在.gitlab-ci.yml中通过tags指定运行节点:
job_on_specific_runner: tags: - runner-1 script: echo "Running on runner-1"6. 安全加固与权限管理
随着自动化程度的提高,安全性变得尤为重要。以下是几个关键的安全实践。
6.1 Runner安全隔离
为不同项目创建隔离的系统用户:
sudo useradd -m -s /bin/bash runner-project1 sudo passwd runner-project1然后在注册Runner时指定用户:
sudo gitlab-runner register --user runner-project16.2 敏感信息管理
使用GitLab CI/CD变量存储敏感信息:
- 进入项目Settings > CI/CD > Variables
- 添加变量如DEPLOY_SSH_KEY、DB_PASSWORD等
- 勾选"Mask variable"和"Protect variable"选项
在脚本中通过环境变量引用:
deploy_job: script: - echo "$DEPLOY_SSH_KEY" > deploy_key - chmod 600 deploy_key - ssh -i deploy_key user@server6.3 审计日志与监控
启用GitLab操作日志:
sudo vim /etc/gitlab/gitlab.rb添加配置:
gitlab_rails['audit_log_enabled'] = true gitlab_rails['audit_log_format'] = 'json' gitlab_rails['audit_log_path'] = '/var/log/gitlab/audit.log'配置日志轮转:
sudo vim /etc/logrotate.d/gitlab-runner添加内容:
/var/log/gitlab-runner/*.log { weekly missingok rotate 12 compress notifempty }在实际项目中,我们发现最常出现的问题是Runner权限不足导致的部署失败。一个实用的技巧是在部署服务器上为Runner配置专用的SSH密钥,并通过~/.ssh/config文件预设连接参数,这样可以避免在CI脚本中暴露过多敏感信息。
