7. Molecule test at role level

It’s good practice to always keep test code next to the components. In the case of a role, this means placing it in the role’s directory.

roles/
  apache/
    meta/
      main.yml
    molecule/
      apache4_with_role/
        converge.yml
        Dockerfile.centos
        Dockerfile.ubuntu
        molecule.yml
        verify.yml
    tasks/
      main.yml

The test file layout is identical; everything is the same except for one difference inside molecule.yml/provisioner/env, where you configure ANSIBLE_ROLES_PATH to point to the repository root where the roles directory is located. I will again use MOLECULE_PROJECT_DIRECTORY, which conveniently contains the path to the tested component. In the case of a role, this is the role’s root directory, which is two levels below the repository root where the roles directory is located. This difference is reflected in the configuration, and it is the only change.

# molecule.yml (fragment)
provisioner:
  name: ansible
  env:
    ANSIBLE_ROLES_PATH: "${MOLECULE_PROJECT_DIRECTORY}/../../roles"

You can go to the role’s home and invoke the test.

cd roles/apache
molecule test -s apache4_with_role