Ansible - efficient use of set_fact with when clause

I have configured several set_fact tasks. However, to me it feels that this is not DRY.

For example, I configure 2 different tasks to set a fact based on a different when clause:

- set_fact:
    installed: false
  when: "'abc' not in ansible_facts.packages"

- set_fact:
    installed: true
  when: "'abc' in ansible_facts.packages"

Another example I use:

- name: set fact for bootstrapper
  set_fact:
    bootstrapper: true
  when: cluster.bootstrapper

- name: set fact for not bootstrapper
  set_fact:
    bootstrapper: false
  when: not cluster.bootstrapper

Q: Is there a more efficient method to set all these facts in e.g. a single task?


Solution 1:

Instead of setting hard-coded boolean values based on boolean conditions, set the variables to the result of evaluating the condition.

- set_fact:
    installed: "{{ 'abc' in ansible_facts.packages }}"
    bootstrapper: "{{ cluster.bootstrapper is truthy }}"

(You may need to adjust the second example depending on the expected contents of cluster.bootstrapper and the version of Ansible that you are using.)