I've seen a few threads about looping over a list on a role, and the currently preferred method seems to be to pass the list as a variable and do the looping in each task.
My problem is that I not only want to use each variable as is, but also construct new variables based on logic over multiple keys in the original list, and that would be used in several different tasks. I'll show an example that hopefully makes more sense, but I seem to run in to this issue over and over again.
In my example case I want to set up multiple virtual hosts on a single server. Some are https and some are not, and I want to make one vhost on each port the default.
I currently have a role that accepts a single vhost parameter, and a playbook where I invoke it once for each virtual host (example is simplified):
---
- role: vhost
vhost:
ssl: yes
primary: yes
- role: vhost
vhost:
ssl: no
primary: yes
- role: vhost
vhost:
ssl: no
primary: no
I then have logic in my role that constructs a path to the config file and a dir where the document root and other virtual host specific files should be placed.
The config file should be "{{ name }}.conf", but to separate the ssl host from the non-ssl for the same domain I want the former to be prefixed with "ssl-". And since this is the primary ssl host it should also be prefixed with "_" to be loaded first. The path to the document root should also include the possible "ssl-"-prefix, and the domain name, but not the "_"-prefix.
To not have to repeat that logic in each task that reference either of the paths, I set up two new variables, vhost_base_name and vhost_config_file, through the "defaults/main.yml" file (and also some intermediate variables):
---
vhost_ssl_prefix: "{{ 'ssl-' if (vhost.ssl|bool) else '' }}"
vhost_base_name: "{{ vhost_ssl_prefix }}{{
vhost.name }}"
vhost_primary_prefix: "{{ '_' if (vhost.primary|bool) else '' }}"
vhost_config_file: "{{ vhost_primary_prefix }}{{ vhost_base_name }}.conf"
---
How could I convert this kind of setup to use a list of vhosts in the role (so I can put the list in a host_vars or group_vars file instead of in a host specific playbook)? The only way I found is to make (local) command tasks that loop over the list and echo new strings and registers them in a new variable. But both the commands and looping over and referencing the results quickly becomes very unreadable, and it makes me think I'm working against the flow of the system.
Regards
/Daniel