I'm configuring a template file in Ansible and I'm having trouble figuring out a way to append values to a list var multiple times.
My setup has multiple groups and roles, each of those could have extra values to append to a global list of routes which is used in a template file.
For example, the route-eth0
template would be:
{% for r in routes_var %}
"{{ r }}"
{% endfor %}
routes_var
is defined at the topmost level in roles/common/defaults/main.yml
, since every host will have this role applied, this is the base:
routes_var:
- "1.2.3.4 via {{ gateway }}"
- "2.3.4.5 via {{ gateway }}"
Then, every other role, group or host should be able to append to this variable so that in the end the full routes file is written with contributions from all of them. The goal is that any groups or roles which need to add routes can do so without having to worry about the rest of them.
For example:
roles/logforwarding/defaults/main.yml
- extra routes for hosts which forward logsroles/monitored/defaults/main.yml
- extra routes for hosts under monitoringgroup_vars/some_hosts.yml
- extra routes for a specific group of hostsgroup_vars/siteA.yml
- extra routes for hosts located in some geographical site- etc.
I've tried the following pattern in these files:
routes_var_this:
- "123.4.5.6 via {{ gateway }}"
- "234.5.6.7 via {{ gateway }}"
routes_var: "{{ routes_var.extend(routes_var_this) }}"
alternatively (with the same result):
routes_var: "{{ routes_var + routes_var_this }}"
However, both of these solutions fail with a recursion error when applying the template:
(...)
original message: An unhandled exception occurred while templating '{{ routes_var.extend(routes_var_this) }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: recursive loop detected in template string: {{ routes_var.extend(routes_var_this) }}"}
Is there a way of achieving this with Ansible?