Ansible Jinja2 模板迭代循环

Ansible Jinja2 template iteration over loop

{% if node_count is defined %}
{% set cnt = node_count|int + 1 %}
{% for i in range(cnt)  %}
            localhost00{{ i + 1 }}.local
{% endfor %}
{% endif %}

我想打印

localhost001.local
localhost002.local
.
.
localhost010.local

我知道我这样做不对,当计数达到 10 时它会打印 localhost0010.local,我希望它打印 localhost010.local

感谢对此的帮助。

您想使用格式来打印前导零。你可以这样做:

{% set node_count = 10 %}
{% if node_count is defined %}
    {% set cnt = node_count|int + 1 %}
    {% for i in range(cnt) %}
        localhost{{ '%03d' % (i + 1) }}<br>
    {% endfor %}
{% endif %}

只需将 3 更改为您需要的任意“位数”即可。

输出:

localhost001
localhost002
localhost003
localhost004
localhost005
localhost006
localhost007
localhost008
localhost009
localhost010
localhost011