Ansible 进 CI/CD = 代码合并自动发布。本文讲两大平台集成与流水线设计,结尾附 GitLab CI 完整案例。
一、集成要点
CI 容器里要:ansible + 剧本仓库 + SSH 私钥 + vault 密码
密钥来源:CI 的 Secret 变量(不要写死)
执行方式:ansible-playbook -i inventory/xxx/hosts.yml site.yml
二、GitLab CI 集成
# .gitlab-ci.yml
image: python:3.11-slim
before_script:
- pip install ansible ansible-lint -q
- mkdir -p ~/.ssh
- echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
- chmod 600 ~/.ssh/id_ed25519
- echo "$VAULT_PASS" > ~/.vault_pass && chmod 600 ~/.vault_pass
stages:
- lint
- test
- deploy-staging
- deploy-prod
lint:
stage: lint
script:
- yamllint .
- ansible-lint site.yml
test-deploy:
stage: test
script:
- ansible-playbook -i inventory/test/hosts.yml site.yml --check --diff
only: [merge_requests]
deploy-staging:
stage: deploy-staging
script:
- ansible-playbook -i inventory/staging/hosts.yml site.yml
--vault-password-file=~/.vault_pass
only: [main]
environment: staging
deploy-prod:
stage: deploy-prod
script:
- ansible-playbook -i inventory/prod/hosts.yml site.yml
--vault-password-file=~/.vault_pass
only: [tags] # 打 tag 才发生产
when: manual # 手动确认
environment: production
GitLab 的 Settings → CI/CD → Variables 存 SSH_PRIVATE_KEY / VAULT_PASS(Masked + Protected)。
三、Jenkins Pipeline
pipeline {
agent any
environment {
ANSIBLE_HOST_KEY_CHECKING = 'False' // Jenkinsfile
}
stages {
stage('Lint') {
steps { sh 'ansible-lint site.yml' }
}
stage('Check') {
steps {
sh 'ansible-playbook -i inv/staging site.yml --check --diff'
}
}
stage('Deploy') {
input { message "确认发布生产?" }
steps {
sh 'ansible-playbook -i inv/prod site.yml'
}
}
}
post {
failure { mail to: 'ops@example.com', subject: "发布失败 ${env.JOB_NAME}" }
}
}
四、流水线阶段设计
lint(语法检查)→ check(演练)→ deploy staging(自动)
→ 验证(健康检查)→ deploy prod(手动/打 tag)→ 通知
| 阶段 | 要点 |
|---|---|
| lint | ansible-lint + yamllint 挡坏代码 |
| check | --check --diff 演练 |
| staging | 自动发布测试环境 |
| prod | manual + tag 触发(双保险) |
| 通知 | 失败告警到钉钉/邮件 |
五、注意
- CI 的 SSH 私钥专用(限定 IP/命令,别用个人密钥);
- vault 密码用 CI Secret 变量;
- 生产发布设 manual + 环境保护规则;
- CI 里 host_key_checking 要关(或预置 known_hosts)。
六、小案例:GitLab CI 发布流水线
# 完整版:带发布状态查询与钉钉通知
deploy-prod:
stage: deploy-prod
only: [tags]
when: manual
script:
- ansible-playbook -i inventory/prod/hosts.yml release.yml
--vault-password-file=~/.vault_pass
-e "version=${CI_COMMIT_TAG}"
- ansible -i inventory/prod/hosts.yml web -m uri
-a "url=http://127.0.0.1/health" # 发布后健康检查
after_script:
- |
curl -X POST "$DINGTALK_WEBHOOK" -H 'Content-Type: application/json' -d "{
"msgtype": "text",
"text": { "content": "发布 ${CI_COMMIT_TAG} 结果: ${CI_JOB_STATUS}" }
}" || true
四要素:tag 触发 + manual 确认 + 健康检查 + 钉钉通知 —— 生产发布流水线的完整形态。
七、总结
CI 容器装 ansible + 注入密钥(Secret 变量);lint→check→staging→prod 四阶段;生产 manual+tag 双保险;发布后健康检查与通知闭环。