Minimizing Conditionals in Ansible

Ansible gives you conditionals to use when you want to check if something meets a certain criteria. For example:

- name: install apache
  package:
    name: httpd
    state: installed
  when: ansible_distribution == 'CentOS'

If you have a lot of these you can separate out specific .yml files to include a conditional:

- include: centos.yml
  when: ansible_distribution == 'CentOS'

However sometimes a cleaner way (in my opinion) is to use a variable to minimize the use of conditional statements. Using the same example with Apache:

tasks/main.yml

- name: install apache
  package:
    name: "{{ apache_package }}"
    state: installed

defaults/main.yml

dist_dict:
  "RedHat":
    apache: 'httpd'
  "Fedora":
    apache: 'httpd'
  "CentOS":
    apache: 'httpd'
  "Ubunu":
    apache: 'apache2'

apache_package: "{{ dist_dict[ansible_distribution]['apache'] }}"

You can take this one step further and utilize that same dictionary for services (and other things) as well.

dist_dict:
  "RedHat":
    apache_package: 'httpd'
    apache_service: 'httpd'
  "Fedora":
    apache_package: 'httpd'
    apache_service: 'httpd'
  "CentOS":
    apache_package: 'httpd'
    apache_service: 'httpd'
  "Ubunu":
    apache_package: 'apache2'
    apache_service: 'apache2'

apache_package: "{{ dist_dict[ansible_distribution]['apache_package'] }}"
apache_service: "{{ dist_dict[ansible_distribution]['service_service'] }}"

Then your tasks could simply be:

- name: install apache
  package:
    name: "{{ apache_package }}"
    state: installed

- name: start apache
  service:
    name: "{{ apache_service }}"
    state: started
    enabled: true

This gives you the power to utilize these variables in other places without including whole .yml files or using a bunch of conditional statements.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s