下面是我在ansible中使用的jinja2模板。
{% set port = 1234 %}
{% set server_ip = [] %}
{% for ip in host_ip %}
{% do server_ip.append({{ ip }}:{{ port }}) %}
{% endfor %}
{% server_ip|join(', ') %}
下面是我想要的输出:
devices = 192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234
但是当我运行ansible playbook时,它抛出了如下错误:
"AnsibleError: teme templating string: Encountered unknown tag 'do'. Jinja was looking for th: 'endfor' or 'else'
如有任何帮助,将不胜感激..
发布于 2018-08-16 07:44:47
这对我很有效:
- set_fact:
devices: >-
{% for ip in host_ip %}{{ ip }}:1234{% if not loop.last %},{% endif %}{% endfor %}
如果您仍然想使用do
,那么可以添加
jinja2_extensions = jinja2.ext.do
添加到ansible配置文件中,并更改
{% do server_ip.append({{ ip }}:{{ port }}) %}` to `{% do server_ip.append({ip:port}) %}`
发布于 2021-09-07 14:59:49
使用map()
和regex
的单线解决方案
{{ ["1.1.1.1","2.2.2.2"]|map('regex_replace', '(.+)', "\\1:1234")|join(', ') }}
map('regex_replace', '(.+)', "\\1:1234")
将:1234
添加到传递的数组(.+)
中的任何非空字符串["1.1.1.1","2.2.2.2"]
。结果:
1.1.1.1:1234, 2.2.2.2:1234
https://stackoverflow.com/questions/49619445
复制相似问题