ansible 角色测试验证应使用 molecule 工具,通过定义 platforms、provisioner 和 verifier 来构建隔离环境并执行自动化检查。配置时需在角色根目录创建 molecule.yml 文件指定基础镜像(如 docker),编写 converge.yml 调用角色逻辑,并使用 testinfra 或 goss 在 tests/ 目录下编写断言脚本。运行 molecule test 即可自动完成环境搭建、角色应用及结果验证。

如何初始化 Molecule 环境并配置基础平台
初始化 Molecule 环境需安装依赖包并在角色目录下运行 molecule init 命令。配置基础平台主要涉及编辑 molecule.yml 中的 platforms 字段,指定容器镜像名称及变量。这一步骤确保了后续测试能在指定的操作系统环境中进行。

pip install molecule docker molecule-plugins[docker] ansible-lint molecule init role -r my_role cd my_role molecule init scenario -n default -d docker
上述命令创建了角色结构并初始化了基于 Docker 的默认场景。生成的 molecule/default/molecule.yml 包含平台配置,例如:
---
platforms:
- name: instance
image: ghcr.io/geerlingguy/docker-centos8-ansible:latest
privileged: true
pre_build_image: true
provisioner:
name: ansible
verifier:
name: ansible
该配置定义了名为 instance 的节点,使用 CentOS 8 镜像,并启用特权模式以支持容器内服务启动。预构建镜像选项可加速重复测试。
如何编写收敛剧本与验证器测试用例
收敛剧本 converge.yml 负责实际应用 Ansible 角色逻辑,而验证器测试用例位于 tests/ 目录中,用于检查结果是否符合预期。通常使用 testinfra 编写 Python 风格的测试脚本,检查文件存在性、服务状态或端口监听情况。
- name: Converge
hosts: all
roles:
- role: my_role
这是标准的收敛剧本,仅引入角色而不添加额外任务。接下来在 tests/common/test_default.py 中编写验证逻辑:
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
m.get_option('inventory.file')
).get_hosts('all')
def test_nginx_installed(host):
nginx = host.package("nginx")
assert nginx.is_installed
def test_nginx_running(host):
nginx_service = host.service("nginx")
assert nginx_service.is_running
assert nginx_service.is_enabled
这些测试用例确保 Nginx 软件包已安装且服务处于运行和启用状态。若测试失败,molecule verify 将返回非零退出码,提示验证未通过。
当测试用例因权限不足导致服务启动失败时应如何处理
当测试用例因权限不足导致服务启动失败时,通常是因为容器内缺少必要的系统服务管理器或权限设置不当。解决方法是在 molecule.yml 中为平台节点添加 privileged: true 属性,或在 converge.yml 中预先安装并启动 systemd。此外,需确保使用的镜像包含完整的系统初始化支持,否则部分服务无法正确注册到系统管理中。










