Ansible - multi distro capable roles

Jun 15, 2015   #ansible 

Something that has been commented on before in #ansible, is the lack of a generic package module. i.e. you have to use either yum, apt, pip etc.

There is a reason this is done, namely, there are some substantial differences between the args taken and even sometimes the package names or service names.

However, if you wish to write roles that can handle many distributions and packaging systems, then there are of course ways of doing so.

They involve a fact provided by the setup module - ansible_pkg_mgr - and use of conditional var files.

For example - there are two main packages which differ between Debian and RHEL based OS’s that immediately spring to mind.

  • ntp/ntpd
  • apache2/httpd

Taking the more obvious apache/httpd as an example

# play.yml
- hosts:
    - apache

Note that we’re using vars/ here, which is not normally recommended as they are high in precedence. However in this case we’re setting application values that we are very unlikely to override.

# roles/apache/vars/redhat.yml
  - httpd
apache_service_name: httpd
apache_config: /etc/httpd/conf/httpd.conf
# roles/apache/vars/debian.yml
  - apache2
apache_service_name: apache2
apache_config: /etc/apache2/apache2.conf
# roles/apache/tasks/main.yml
- include_vars: "{{ ansible_os_family | lower }}.yml"

- name: install apache
  action: "{{ ansible_pkg_mgr }}"
    name: "{{ apache_package_name }}"
    state: present

- name: configure apache
    src: "{{ apache_config | basename }}.j2"
    dest: "{{ apache_config }}"
  notify: restart apache

- name: ensure apache is started and starts on boot
    name: "{{ apache_service_name }}"
    state: started
    enabled: yes
# roles/apache/handlers/main.yml
- name: restart apache
    name: "{{ apache_service_name }}"
    state: restarted

Note: You can see more about this and other tips and tricks in Brian Coca’s (bcoca) slides tips and tricks he presented during the Ansible Fest in NYC 2015