Ansible repeating roles

Solution 1:

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.

Solution 2:

What I do is I create roles apache, which installs apache and does some configuration for all vhosts, apache-vhost, which installs a vhost, host1-com, and other-com. Then the playbook would be like this:

- hosts: host1-com-servers
  roles:
    - apache
    - host1-com

- hosts: other-com-servers
  roles:
    - apache
    - other-com

Now, host1-com will have this:

- meta:
  - dependencies:
    - role: apache-vhost
      server_name: host1.com
      server_aliases:
        - www.host1.com
      extras: |
        Alias /static /var/local/myapp/static
        <Location /static>
          Require all granted
        </Location>
        # Whatever else you want
      whatever_other_variables_apache-vhost_needs: XXX

(This is an implementation detail, but the apache-vhost role prepares some essential vhost configuration based on the variables passed to it, and also adds the extras variable as is inside the vhost configuration.)

Likewise for the databases, you can have a postgresql role, a postgresql-database role, and so on.