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)