问题
We're trying to come up with a way to use ansible facts within jinja2 For Loops.
For example, I want to get all servers that belong to my memcached group as well as a group based on release (something like tag_release_dev
or tag_release_prod
). When I try to use {{ tt_release }}
within the For Loop it evaluates {{ tt_release }}
rather than the value of the variable. Is there a way to use a variable within the loop definition?
{% for host in groups["tag_function_mem"] | intersect(groups["tag_release_{{ tt_release }}"]) %}
{{ host }}:11211
{%- if not loop.last %},{% endif %}
{%- if loop.last %}"{% endif %}
{% endfor %}
{% endif %}
回答1:
it evaluates
{{ tt_release }}
rather than the value of the variable.
This is because you already are inside a expression. You can not nest expressions - and you don't need to.
What you want is to concatenate the string "tag_release_"
and the variable tt_release
. In Jinja2 concatenation is done with a +
.
{% for host in groups["tag_function_mem"] | intersect(groups["tag_release_" + tt_release]) %}
来源:https://stackoverflow.com/questions/38212684/variable-in-jinja2-for-loop