Group by if variable is true in Ansible

One way of selecting wether to apply a role or not in Ansible is to set variables like “webserver: True” or “mysql: True” on the hosts and then in playbook do

- { role: webserver, when: webserver is defined and webserver }

Another is to have the host member of groups and have plays like:

- hosts: webserver
  roles: webserver

I find the latter more flexible and to my liking. Sometimes you have both and need to bring them together. This can be done with the ansible action  group_by

- hosts: all
  connection: local
  gather_facts: false

tasks:
 - group_by:
 key: "{% if webserver is defined and webserver %}webserver{% endif %}"
 name: group_by(webserver)
 - group_by:
 key: "{% if mysql is defined and mysql %}mysql{% endif %}"
 name: group_by(mysql)

 

Advertisements

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