Skip to content

Ansible Notes

John Pellman edited this page Mar 17, 2020 · 1 revision

Ansible Notes

Various thoughts/meditations on Ansible and Ansible playbooks.

Conditionals

Running the following repeatedly is the same as having a bunch of if/elif/else statements in a row (from ansible-guacamole):

- name: Setting a fact.
  set_fact:
    my_great_fact: foobar
when: >
    (ansible_distribution == "Debian") or
    (ansible_distribution == "Ubuntu")

- name: Setting a fact.
  set_fact:
    my_great_fact: fizzbuzz
when: >
    (ansible_distribution == "RedHat")

In contrast, this is the Ansible equivalent to a switch/case statement (from ansible-anaconda by Andrew Rothstein):

- name: resolve platform specific vars
  include_vars: "{{ item }}"
  with_first_found:
    - files:
        - '{{ ansible_os_family }}.yml'
        - 'default.yml'
      paths:
        - '{{ role_path }}/vars'

Ansible switch/case statements are preferable because fewer conditionals need to be evaluated and case statements are more maintainable / grokkable. In the case/statement, all that needs to happen is for ansible_os_family to be expanded once, while in the other example ansible_distribution is expanded three times and two when statements need to be evaluated.

Clone this wiki locally