gitlab ci 动态加载配置的核心是通过 include 结合变量、rules 和脚本实现环境化配置管理:支持变量控制 local 路径引入 yaml 片段、rules 保障条件触发安全、artifact 引入运行时生成的配置,以及 variables 覆盖简化轻量场景。

GitLab CI 在部署时动态加载配置,核心是让流水线能根据环境、分支、触发条件等实时决定加载哪套配置,而不是写死在 .gitlab-ci.yml 里。这不仅能减少重复配置,还能提升多环境管理的灵活性和可维护性。
用 include 动态引入配置文件
GitLab 支持通过变量控制 include 的路径,从而加载不同环境的 YAML 片段:
include: - local: '$CI_ENVIRONMENT/deploy.yml' - template: Auto-DevOps.gitlab-ci.yml
只要 $CI_ENVIRONMENT 被正确定义(比如在项目 Settings → CI/CD → Variables 中设为 staging),GitLab 就会尝试加载 staging/deploy.yml。注意:该路径必须存在于仓库根目录下,且是普通 YAML 文件(不能是模板或远程 URL,除非用 remote 并确保可访问)。
配合规则(rules)做环境分流
光靠 include 不够安全——万一变量为空或拼错,可能加载失败。建议加一层 rules 保护:
staging_deploy:
stage: deploy
script: ./deploy.sh
rules:
- if: '$CI_ENVIRONMENT == "staging"'
include:
- local: 'environments/staging.yml'
prod_deploy:
stage: deploy
script: ./deploy.sh
rules:
- if: '$CI_ENVIRONMENT == "production" && $CI_COMMIT_TAG =~ /^v[0-9]+/'
include:
- local: 'environments/prod.yml'
这样每个作业只在满足条件时才生效,也只加载对应配置,避免误触发。
用脚本生成临时配置再 include
如果配置需从外部服务拉取(如 Consul、Vault 或 API),可在作业中先获取并写入临时文件,再用 include: artifact 引入:
fetch_config:
stage: setup
script:
- curl -s "$CONFIG_API_URL?env=$DEPLOY_ENV" > config.yml
artifacts:
paths: [config.yml]
deploy_with_dynamic_config:
stage: deploy
script: ./deploy.sh
needs: ["fetch_config"]
include:
- artifact: config.yml
job: fetch_config
这个方式适合配置频繁变更或含敏感信息(不建议硬编码在仓库中)的场景。
变量驱动的配置覆盖更轻量
对简单差异(如域名、端口、镜像 tag),不必拆文件,直接用 variables + rules 覆盖:
deploy:
stage: deploy
script: echo "Deploying to $DEPLOY_HOST:$DEPLOY_PORT"
variables:
DEPLOY_HOST: "default.example.com"
DEPLOY_PORT: "8080"
rules:
- if: '$CI_ENVIRONMENT == "staging"'
variables:
DEPLOY_HOST: "staging.example.com"
DEPLOY_PORT: "80"
- if: '$CI_ENVIRONMENT == "production"'
variables:
DEPLOY_HOST: "app.example.com"
DEPLOY_PORT: "443"
这种方式无需额外文件,适合中小规模项目快速适配。
不复杂但容易忽略











