编写 .gitlab-ci.yml 实现多阶段(lint→test→deploy)。

解读

在国内企业的 GitLab CI/CD 实践中,面试官希望看到候选人能把 Ansible 的“质量内建”理念落地到流水线。三阶段不是简单堆砌 job,而是要体现:

  1. lint 阶段必须包含 ansible-lint、yamllint,甚至 ansible-playbook --syntax-check,确保剧本符合社区规范与公司编码规约;
  2. test 阶段需要动态创建/销毁测试库存(inventory),用 molecule 或 ansible-test 在 Docker/Podman 容器里跑 idempotence 与断言,输出 JUnit XML 供 GitLab 解析;
  3. deploy 阶段要区分非生产灰度与生产发布,通过 GitLab environment:url 与 only/except 或 rules:if 实现人工审批(when: manual)与变量降级(CI_COMMIT_REF_NAME == "main"),并集成企业微信/飞书机器人做通知。 整个文件必须缓存依赖(.ansible/galaxy_cache)、并发安全(resource_group)且密钥不落盘(通过 GitLab CI/CD Variables + ANSIBLE_VAULT_PASSWORD_FILE)。

知识点

  • ansible-lint 6.x 规则集(yaml、command-instead-of-shell、name[casing])
  • molecule 场景(default、verify、idempotence)与 Podman 驱动
  • GitLab CI 阶段顺序(stages: 声明)与 artifacts:reports:junit 消费
  • SSH 私钥注入(SSH_PRIVATE_KEY → ssh-agent)与 known_hosts 扫描
  • ansible-galaxy cache(--force-with-deps + cache:key:files: requirements.yml)
  • environment 的 deployment_tier: production 与 rollback(ansible-playbook rollback.yml --extra-vars "tag=$CI_COMMIT_SHORT_SHA")
  • 中国式合规:等保 2.0 要求对运维操作留痕,因此要在 playbook 里开启 callback plugin syslog_json,并在 .gitlab-ci.yml 里把日志归档到 S3 兼容存储(如 MinIO)

答案

# .gitlab-ci.yml 示例,基于国内 GitLab 13.12+ 与企业微信通知
stages:
  - lint
  - test
  - deploy

variables:
  ANSIBLE_FORCE_COLOR: "1"
  ANSIBLE_VAULT_PASSWORD_FILE: "$CI_PROJECT_DIR/.vault-pass"
  MOLECULE_DRIVER: "podman"

cache:
  key:
    files:
      - requirements.yml
  paths:
    - .ansible/galaxy_cache/

before_script:
  - mkdir -p ~/.ssh && chmod 700 ~/.ssh
  - echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa
  - ssh-keyscan -p 22 10.0.0.0/8 >> ~/.ssh/known_hosts  # 内网网段示例
  - python3 -m venv venv && source venv/bin/activate
  - pip install -r requirements.txt  # 包含 ansible-core、ansible-lint、molecule[podman]、pytest-testinfra
  - ansible-galaxy collection install -r requirements.yml -p .ansible/galaxy_cache --force-with-deps

lint:
  stage: lint
  script:
    - yamllint .
    - ansible-lint --parseable --nocolor
    - ansible-playbook site.yml --syntax-check -i inventories/test
  artifacts:
    reports:
      codequality: gl-code-quality-report.json  # ansible-lint --format=codeclimate > gl-code-quality-report.json
    expire_in: 1 week
  only:
    - merge_requests
    - main

test:
  stage: test
  parallel:
    matrix:
      - SCENARIO: [default, centos8, ubuntu20]
  script:
    - molecule test -s $SCENARIO
  coverage: '/Coverage: (\d+\.\d+)%/'
  artifacts:
    reports:
      junit: molecule/$SCENARIO/report.xml
    paths:
      - molecule/$SCENARIO/
    expire_in: 1 week
  resource_group: molecule  # 防止并发测试端口冲突

deploy_staging:
  stage: deploy
  script:
    - echo "$VAULT_PASS" > .vault-pass
    - ansible-playbook -i inventories/staging site.yml --tags "apps,config" -e "git_sha=$CI_COMMIT_SHORT_SHA"
  environment:
    name: staging
    url: https://staging.example.com
    deployment_tier: staging
  only:
    - main
  when: manual
  after_script:
    - |
      curl -X POST https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=$WECHAT_KEY \
        -H 'Content-Type: application/json' \
        -d "{\"msgtype\":\"text\",\"text\":{\"content\":\"Ansible 已部署 staging,版本 $CI_COMMIT_SHORT_SHA\"}}"

deploy_prod:
  stage: deploy
  script:
    - echo "$VAULT_PASS" > .vault-pass
    - ansible-playbook -i inventories/prod site.yml --tags "apps,config" -e "git_sha=$CI_COMMIT_SHORT_SHA"
    - ansible-playbook -i inventories/prod rollback.yml --check  # 预演回滚
  environment:
    name: production
    url: https://www.example.com
    deployment_tier: production
  only:
    - main
  when: manual
  resource_group: prod_deploy  # 串行发布
  after_script:
    - |
      curl -X POST https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=$WECHAT_KEY \
        -d "{\"msgtype\":\"text\",\"text\":{\"content\":\"Ansible 已发布生产,版本 $CI_COMMIT_SHORT_SHA,回滚命令:ansible-playbook rollback.yml -e tag=$CI_COMMIT_SHORT_SHA\"}}"

拓展思考

  1. 蓝绿/金丝雀:在 deploy 阶段引入 ansible-runner 与 Argo Rollouts,通过 label 动态切换 Service Endpoint,实现零中断发布。
  2. 合规审计:把 syslog_json 日志实时送到 ELK 或 阿里云 SLS,并配置 WAF 联动,满足等保 2.0 三级对运维审计的要求。
  3. 多集群分发:利用 ansible-core 2.14+ 的 inventory plugins 动态拉取 Nacos 或 Consul 服务列表,实现边缘 K8s 集群的 ConfigMap 热更新。
  4. 密钥轮换:将 Ansible Vault 主密钥托管在 阿里云 KMS,通过 GitLab CI/CD 的 ID Token 换取临时凭证,每小时自动轮换,杜绝长期 Vault 密码泄露风险。
  5. 性能优化:对超大规模(>5 000 节点)使用 Ansible 的 “free” 策略 与 pipelining = True,并在 .gitlab-ci.yml 里启用 custom runner 的 cgroup v2 限制 CPU,把 fork 数动态调到 50–100,实现分钟级全量发布。