ansiblemolecule

Test failure of a playbook with Ansible Molecule


I'm creating a sudo role and want to test with Molecule that the role fails if a rule is not correct.

How can we define that we expect the playbook to fail with Molecule?

For example, if I have the following configuration:

sudo__entries:
  - name: super_alice
    content: "alice ALL NOPASSWD"

The role will fail because visudo won't validate the file.

And that's the behavior I want to test.


Solution

  • You can modify converge.yml to test a failure scenario with a rescue block, using a similar method to this unit testing paradigm:

    try {
        foo();
        Assert.fail();
    } catch(FooException e) {
        // Caught expected exception from foo()
    }
    

    An example failure scenario for role sudo would have a converge.yml that looks something like:

    ---
    - name: Does not converge
      hosts: all
      tasks:
        - block:
            - name: "Include sudo"
              include_role:
                name: "sudo"
              register: expected_failure
            - name: "Check execution halted"
              fail:
                msg: "Execution should stop before this task"
              register: should_not_run
          rescue:
            - assert:
                that:
                  - expected_failure is defined
                  - should_not_run is not defined
    

    You can also supplement this with a verify.yml to assert the failure scenario did not leave the host in a broken state.