
.gitlab-ci.yml
文件是 GitLab CI/CD 的核心配置文件,用于定义项目的自动化构建、测试和部署流程。以下是配置 .gitlab-ci.yml
文件的基本步骤:
.gitlab-ci.yml
文件在您的项目根目录下创建一个名为 .gitlab-ci.yml
的文件。这个文件将包含所有的CI/CD管道配置。
首先,需要定义 CI/CD 流程中的各个阶段。通常包括 build
(构建)、test
(测试)和 deploy
(部署)等阶段。
stages:
- build
- test
- deploy
在每个阶段,您可以定义一个或多个作业。作业包含了具体的执行步骤,比如编译代码、运行测试、部署应用等。
构建作业:
build_job:
stage: build
script:
- echo "Building the project..."
- ./build_script.sh # 执行构建脚本
artifacts:
paths:
- build/ # 保存构建生成的文件
测试作业:
test_job:
stage: test
script:
- echo "Running tests..."
- ./test_script.sh # 执行测试脚本
部署作业:
deploy_job:
stage: deploy
script:
- echo "Deploying the application..."
- ./deploy_script.sh # 执行部署脚本
environment:
name: production # 定义部署环境
url: http://your-production-url.com # 部署后的访问地址
only:
- master # 仅在 master 分支上运行部署作业
您可以根据项目需求设置作业的触发条件。例如,某些作业仅在特定分支或标签上运行。
build_job:
stage: build
script:
- echo "Building the project..."
- ./build_script.sh
only:
- master # 仅在 master 分支上运行
仅在标签(tags)上运行作业:
deploy_job:
stage: deploy
script:
- echo "Deploying the application..."
- ./deploy_script.sh
only:
- tags # 仅在创建标签时运行
缓存可以加速CI流程,通过存储和重用在不同作业或管道中生成的文件。
cache:
paths:
- node_modules/ # 缓存依赖
如果作业需要额外的服务(如数据库、Redis等),可以在 .gitlab-ci.yml 中定义服务。
services:
- mysql:latest # 使用最新版本的 MySQL 服务
您可以在 .gitlab-ci.yml 文件中定义和使用环境变量。
variables:
DATABASE_URL: "mysql://user:password@mysql/db"
build_job:
stage: build
script:
- echo $DATABASE_URL # 使用环境变量
GitLab CI/CD 允许您基于条件配置管道的执行逻辑。
使用 rules 配置:
build_job:
stage: build
script:
- echo "Building the project..."
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
配置完成后,可以通过 GitLab 的 CI Lint 工具来验证 .gitlab-ci.yml 文件的正确性。
最后,将 .gitlab-ci.yml 文件提交到项目的仓库中,GitLab 会自动检测到该文件,并启动 CI/CD 流水线。
stages:
- build
- test
- deploy
build_job:
stage: build
script:
- echo "Building the project..."
- ./build_script.sh
artifacts:
paths:
- build/
only:
- master
test_job:
stage: test
script:
- echo "Running tests..."
- ./test_script.sh
deploy_job:
stage: deploy
script:
- echo "Deploying the application..."
- ./deploy_script.sh
environment:
name: production
url: http://your-production-url.com
only:
- tags
通过这些步骤,您可以在 GitLab 项目中配置 .gitlab-ci.yml
文件,自动化您的构建、测试和部署流程。