Ansible repeating roles

ansible

I use Ansible to manage some web- and database servers which run websites for multiple vhosts. For each website I need to assign a database role to the dbservers group and a website role to the webservers group. So my playbook looks something like this:

- hosts: dbservers
  roles: 
      - { role: database, vhost: 'host1.com', db: 'customdb' }
      - { role: database, vhost: 'other.com' }

- hosts: webservers
  roles: 
      - { role: website, vhost: 'host1.com', db: 'customdb' }
      - { role: website, vhost: 'other.com' }

This works well, but it is ugly as I have to repeat everything twice. This is especially error-prone when changing some parameters from the default values (like db on vhost host1.com in this example).

Is there a way to write this so I can have a single list of vhosts with all the required parameters and automatically add the different roles to the different host groups for each vhost entry?

Best Answer

the most obvious answer - use complex variables (dictionaries) to hold your values, and then pass entire variable:

- layouts:
  - layout1:
      vhost: host1.com
      db: customdb
  - layout2:
      vhost: other.com

then use those to pass over to roles:

- hosts: dbservers
  roles:
  - { role: database, layout: layouts.layout1 }
  - { role: database, layout: layouts.layout2 }

- hosts: webservers
  roles:
  - { role: webserver, layout: layouts.layout1 }
  - { role: webserver, layout: layouts.layout2 }

I've done this successfully in the past. To populate layouts you can use various techniques: combining "group_vars/all" with "vars_files" with "host_vars" etc.