Ansible Jinja2模板迭代遍历

问题描述

{% 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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...