4

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.

  • I did not yet find a correct way of doing this myself in a satisfying way. Meanwhile you might be interested in the [`side effect` step](https://molecule.readthedocs.io/en/stable/usage.html#side-effect) which is not enabled by default (see [ansible provionner doc](https://molecule.readthedocs.io/en/stable/configuration.html#id22)) – Zeitounator Dec 05 '19 at 09:35
  • I found documentation on [this page](https://blog.octo.com/the-wizard-side-effects/) of what is side effect, but is does not help testing the failure of a playbook. I updated my question with an example. – Alexandre Salomé Dec 05 '19 at 10:35

1 Answers1

2

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.

ParkerM
  • 302
  • 1
  • 4
  • 17