GitLab CI/CD脚本入门
# 全局配置
stages: # 定义各个阶段
- setup
- build
- test
- deploy
variables: # 全局变量设置
NODE_ENV: "development"
PACKAGE_VERSION: "1.0.0"
GIT_SUBMODULE_STRATEGY: "recursive" # 设置git子模块策略
before_script: # 全局的before_script,适用于所有job
- echo "Setting up the environment"
- apt-get update -y
- apt-get install -y python3-pip
# Cache设置,适用于所有的job
cache:
paths:
- node_modules/
- .cache/pip
setup_job: # setup 阶段的 job
stage: setup
image: node:16
script:
- npm install
artifacts:
paths:
- node_modules/
build_job: # build 阶段的 job
stage: build
image: node:16
script:
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 week # 设置 artifacts 的过期时间
test_job: # test 阶段的 job
stage: test
image: node:16
dependencies: # 声明依赖于 build_job 的 artifacts
- build_job
script:
- npm run test
cache: # 局部 cache 配置,覆盖全局配置
paths:
- .cache/
test_python: # 另一个 test 阶段的 job,用 Python 执行测试
stage: test
image: python:3.9
script:
- pip install -r requirements.txt
- pytest
artifacts:
paths:
- test-reports/
reports:
junit: test-reports/report.xml # 生成 JUnit 格式的测试报告
manual_deploy: # deploy 阶段的 job,手动执行
stage: deploy
script:
- echo "Deploying to production server..."
when: manual # 手动触发
only:
- master
auto_deploy: # 自动部署,允许失败
stage: deploy
script:
- echo "Deploying to staging server..."
environment: # 设置环境变量
name: staging
url: https://staging.example.com
allow_failure: true # 部署失败不影响 pipeline 成功状态
pages: # 使用 GitLab Pages 部署静态站点
stage: deploy
script:
- echo "Building static pages"
- mkdir .public
- echo "<html><body><h1>My Project</h1></body></html>" > .public/index.html
artifacts:
paths:
- .public
only:
- master
retry_example: # 设置失败后自动重试
stage: test
script:
- echo "This will retry on failure"
- exit 1
retry: 2 # 失败时重试2次
timeout_example: # 设置超时
stage: test
script:
- echo "This job has a timeout"
- sleep 120
timeout: 1m # 超时时间1分钟
# 使用extends继承配置
.base_job_template: # 定义一个基础job模板
image: alpine:latest
before_script:
- echo "This is before script from base template"
script:
- echo "Running from base template"
my_extended_job:
extends: .base_job_template # 继承模板
script:
- echo "This is an extended job"
# Docker in Docker 服务示例
docker_build:
stage: build
image: docker:latest
services:
- docker:dind # 使用 Docker in Docker
script:
- docker build -t myapp .
only_master_branch: # 只在 master 分支上运行的 job
stage: test
script:
- echo "This runs only on the master branch"
only:
- master
except_develop_branch: # 除了 develop 分支外,所有分支都运行的 job
stage: test
script:
- echo "This runs on all branches except develop"
except:
- develop