深色模式
自动化测试:对 playbook/模块校验
摘要:基础设施代码也是代码,同样需要测试。本文搭建由浅入深的四层校验:语法 → 风格 lint → Molecule 单元式测试 → 集成验证,并给出可放进 CI 的配置。
适用环境
- Linux 控制机,Python 3.9+
- 已有 Ansible playbook/role 或 Terraform 模块
- 可选:Docker(Molecule 的 Docker driver 需要)
操作步骤
1. 第一层:语法与风格(最便宜)
bash
ansible-playbook site.yml --syntax-check
terraform fmt -check -recursive && terraform validate
pip install yamllint ansible-lint && yamllint . && ansible-lint roles/nginx1
2
3
2
3
秒级完成,应放在 CI 最前面。用 .ansible-lint 的 exclude_paths / skip_list 管理例外。
2. 第二层:Molecule 做角色测试
bash
pip install molecule molecule-plugins[docker]
cd roles/nginx && molecule init scenario default --driver-name docker
molecule test # 一条命令跑完 create → converge → verify → destroy1
2
3
2
3
验证脚本用 testinfra 写(tests/test_default.py):
python
def test_nginx_is_installed(host):
assert host.package("nginx").is_installed
def test_nginx_is_running(host):
svc = host.service("nginx")
assert svc.is_running and svc.is_enabled
def test_port_is_listening(host):
assert host.socket("tcp://0.0.0.0:80").is_listening1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
3. 第三层:Terraform 模块集成测试
bash
curl -s https://raw.githubusercontent.com/terraform-linters/tflint/master/install_linux.sh | bash
tflint --init && tflint
cd examples/complete # 在测试账号/沙箱真实演练
terraform init && terraform apply -auto-approve
terraform output -json | jq -e '.instance_id.value != ""'
terraform destroy -auto-approve1
2
3
4
5
6
2
3
4
5
6
4. 接入 CI
yaml
- name: Lint
run: |
yamllint .
ansible-lint
terraform fmt -check -recursive
- name: Molecule
run: molecule test --all1
2
3
4
5
6
7
2
3
4
5
6
7
危险
Molecule/Terraform 集成测试会真实创建资源。务必使用独立测试账号与独立 state,并配置预算告警。
验证
bash
ansible-lint roles/nginx && molecule test && tflint1
- [ ] CI 中语法与 lint 失败时流水线立即中断
- [ ] Molecule 能完整跑通 create → converge → verify → destroy
- [ ] 故意改坏一个任务,测试能捕获失败
常见坑
Molecule 需要 Docker
CI 中需启用 docker-in-docker 或挂载 socket,权限配置不当会一直报连接失败。
testinfra 服务名因发行版而异
不少服务在不同发行版名字不同(如 ssh vs sshd)。测试要在与实际一致的镜像上跑。
lint 规则随版本变化
升级 ansible-lint 后可能突然多出大量告警。在 CI 中固定版本号。