patch0110
patch0110

Reputation: 27

Ansible - Using logical AND with "When" to stop skipping second evaluation

Context

I've written a playbook that collects users in a group and registers the stdout_lines in a variable.
If on all hosts there are no users in the group, then I want to end the play as there is nothing to be done.
This is how I am currently evaluating that:

- name: Stopping play if no users in group
  block:
    - debug:
        msg: "No users found - ending play"

    - meta: end_play
  when: users_found | length == 0

The Problem

Say "Host1" has no users within the group, but "Host2" has users within the group...
If Host1 is evaluated first, the condition holds true which results in the evaluation of Host2 being skipped and the playbook ending. This gives the following output on the command line:

ok: [*ip Host1*] => {
"msg": "No training accounts found - ending play"
}
skipping: [*ip Host2*]

A Solution

There is the obvious solution by changing the condition on the when statement to:

hostvars['*ip Host1*'].users_found | length == 0 and hostvars['*ip Host2*'].users_found | length == 0

But this is a bit rubbish, as in the future I may want to expand my inventory file to include more than 2 hosts. Is there a way of making sure ansible evaluates the condition for all hosts listed for the play? Or is there a different approach entirely to this problem? Is it worth combining the lists of users and evaluating based on the cumulative list instead?

Thanks - P

Upvotes: 1

Views: 245

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

End the host instead of the play

- name: Stopping host if no users in the group
  block:
    - debug:
        msg: No users found - ending host
    - meta: end_host
  when: users_found | length == 0

Upvotes: 2

Related Questions