I'm having the following problem templating an ansible vars file that's included in my role in the two following specific ways and I'm wondering if there's a correct way to do this, or if it's just something ansible can't do out of the box due to yaml parser limitations. Best thoughts are appreciated.
Please note the constraint that I'm working entirely with a vars include for this, I am well aware I could include tasks and build the logic that way, but that is sub-optimal for my design.
Issue #1: Dynamically setting content with jinja templating in a vars file.
In regard to strings, something like this works really well:
fqdn: "{% if condition %}
.mydomain.io
{% else %}
.blah.net
{% endif %}"
However, the issue comes into play when attempting this same logical flow with a list, such as:
network_dns:
- {% if condition %}8.8.8.8{% endif %}
- {% if condition %}8.8.4.4{% endif %}
This DOES work, but it's messy and it leaves empty list items where the logic isn't met. Not entirely an isse because I tend to go overboard makign sure I trim my list inputs in my roles, but messy. Sadly, it's not always a this or that flow either, and I have some items that would set 3-4 values in a list, meaning that I need 3-4 like conditional lines since I can't set multiple list items in a single list item without creating a sub list. Really looking for what the best method is here.
Issue #2: list recursion 'max recursion depth reached' More ideally would be something like this:
network_dns: "{{ network_dns | d([]) + {% if condition %}['8.8.8.8','8.8.4.4']{% else %}[]{% endif %} }}"
or even (but slightly less ideal still) assign a temp var to condition and add multiple values would be better:
temp_vars_net_dns: "{% if condition %}['8.8.8.8','8.8.4.4']{% else %}[]{% endif %}"
network_dns: "{{ network_dns | d([]) + temp_vars_net_dns }}"
However, whenever I attempt to combine lists like this in a vars file, I always run into a 'max recursion depth reached' issue, because the parser doesn't fully unpack the list var before it appends items, so it recursively iterates through the appended items forever and ever and ever and ever and... well, you get the idea.
Again, not looking for the perfect infallible solution (unless you have it), just looking for something to make this a bit easier to manage in terms of vars organization.
It actually should not because it's not a valid YAML. This is a reason why it's recommended to always surround the Jinja templates with quotes.
Easy - there's
ternaryfilter designed specifically for this case:The same can be applied to
network_dnsvariable. I would recommend, however, to define the list of IPs separately to ease the things:So, no need for if-else - these usually go against Ansible principles of simplicity.