//home | tags | archives | about | grosu.nl | eulinux.org | RSS Feed

Ansible: Using conditional role dependencies

floyd - Tue 19 January 2016 - ansible, tips, linux

TL;DR: You can use when: in ${role}/meta/main.yml

A while ago I started using Ansible to provision some aspects of my lab and servers. At some point, for one of the roles being worked on (some elasticsearch mini-cluster in this particular case), a specific role needed to be applied to some servers, but only when a condition was met. There are a few ways in which this can be achieved:

Include your roles for specific hosts only, in site.yml, e.g:

# site.yml
- name: configure the elasticsearch cluster
  hosts:
    - elasticsearch_servers
  roles:
    - elasticsearch
- name: configure the data indexers on the master node only
  hosts:
    - elasticsearch_masters
  roles:
    - es_indexer

The above will work just as intended, but IMHO it's not too elegant, and requires you to define a second elasticsearch_masters host group.

Or, use role dependencies, by configuring a meta/main.yml to the elasticsearch role:

# roles/elasticsearch/meta/main.yml
---
dependencies:
  - role: es_indexer

However, this will apply the es_indexer to all the elasticsearch nodes. With only a small change we can beat it into submission: by using the when keyword:

# roles/elasticsearch/meta/main.yml
---
dependencies:
  - role: es_indexer
    when: es_master_node == True

Just remember to define es_master_node = True in your host_vars for the specific nodes (or use some other external variable if you have a dynamic inventory script with an external data source)