You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何成功执行Molecule入门并解决Ansible角色未找到问题?

用Molecule测试Ansible角色时遇到角色找不到的问题

我按照Molecule入门指南操作,尝试通过converge playbook运行名为my_role的角色,converge.yml内容如下:

---
- name: Converge
  hosts: all
  gather_facts: false
  tasks:
    - name: Replace this task with one that validates your content
      ansible.builtin.debug:
        msg: "This is the effective test"
  roles:
    - my_role

但始终遇到错误:ERROR! the role 'my_role' was not found in ...。我试过以下方法都无法解决:

  • 将角色目录链接到~/.ansible/roles等默认角色路径
  • 创建ansible_collections目录
  • 使用localhost驱动测试
  • 使用docker驱动测试

网上多数示例针对旧版本,找不到适配当前版本的正确操作方式。我的Molecule版本信息:

molecule --version
molecule 25.5.0 using python 3.12
    ansible:2.18.6
    default:25.5.0 from molecule
    gce:23.7.0 from molecule_plugins requiring collections: google.cloud>=1.0.2 community.crypto>=1.8.0
    azure:23.7.0 from molecule_plugins
    openstack:23.7.0 from molecule_plugins requiring collections: openstack.cloud>=2.1.0
    podman:23.7.0 from molecule_plugins requiring collections: containers.podman>=1.7.0 ansible.posix>=1.3.0
    ec2:23.7.0 from molecule_plugins
    vagrant:23.7.0 from molecule_plugins
    docker:23.7.0 from molecule_plugins requiring collections: community.docker>=3.10.2 ansible.posix>=1.4.0
    containers:23.7.0 from molecule_plugins requiring collections: ansible.posix>=1.3.0 community.docker>=1.9.1 containers.podman>=1.8.1

适配Molecule 25+的正确测试步骤

1. 初始化Molecule场景(独立角色)

如果测试的是独立角色,直接在角色根目录执行初始化命令:

molecule init scenario default --driver-name docker

该命令会自动生成.molecule目录及默认场景文件(包括converge.yml、molecule.yml),无需手动创建基础配置。

2. 确保目录结构合规

角色目录需遵循Ansible标准结构,Molecule会自动识别当前目录为角色路径:

my_role/
├── defaults/
├── handlers/
├── meta/
├── molecule/
│   └── default/
│       ├── converge.yml
│       ├── molecule.yml
│       └── verify.yml
├── tasks/
├── templates/
└── vars/

3. 修正converge.yml写法

自动生成的converge.yml已默认引入当前角色,若手动编写,确保角色引用正确:

---
- name: Converge
  hosts: all
  gather_facts: false
  roles:
    - my_role

如果角色不在当前目录,可通过include_role指定路径:

- name: Converge
  hosts: all
  gather_facts: false
  tasks:
    - ansible.builtin.include_role:
        name: my_role
        dir: ../path/to/my_role

4. 检查molecule.yml配置

确保provisioner部分未错误覆盖roles_path,默认配置已包含当前目录:

provisioner:
  name: ansible
  config_options:
    defaults:
      roles_path: ${MOLECULE_PROJECT_DIRECTORY}:../:~/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles

5. 执行测试

在角色根目录运行完整测试:

molecule test

或分步执行:

molecule create  # 创建测试容器
molecule converge # 运行playbook
molecule verify  # 验证角色效果
molecule destroy # 销毁测试环境

排查要点

  • 角色目录名称与playbook中引用的名称完全一致(大小写敏感)
  • 不要手动修改roles_path,避免破坏Molecule默认路径配置
  • 若测试集合内的角色,需用集合方式初始化:molecule init scenario default --collection-name namespace.collection

内容的提问来源于stack exchange,提问作者MaKaNu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 22:00:15