Minimize conditionals with Ansible
-
So in Ansible you can use conditionals when a fact is different between systems (eg distribution, release, ip address, etc). You can also use variables with dictionaries and facts to accomplish this. Here is an example using a dictionary with package names for Apache:
--- # vars file for test dist_hash: "RedHat": webserver: 'httpd' "Fedora": webserver: 'httpd' "Ubuntu": webserver: 'apache2' webserver: "{{ dist_hash[ansible_distribution]['webserver'] }}"
The variable that will be called in the task is at the bottom. That variable references the hash (dictionary) above it. So it looks in dist_hash for the distribution (in my case Fedora) and replaces
ansible_distribution
with the actual name. Then it looks at the webserver value of the hash under that distribution name.I set up a simple task that copies a template called
test.j2
with these contents:We will install {{ webserver }} on this system.
The main task file is this:
--- # tasks file for test - name: test template: src: test.j2 dest: /tmp/test.conf owner: root group: root mode: 0644
So it copies
test.j2
and fills in the variable and stores it as/tmp/test.conf
. Here's the output of that file:[jhooks@starscream tmp]$ cat test.conf We will install httpd on this system.
This is one way to keep conditionals to a minimum in your roles.