Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

- 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 :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading