【发布时间】:2019-09-03 12:30:41
【问题描述】:
我正在尝试在 Jinja2 中使用 python 执行 for 循环,该循环将创建并附加到一个列表 - 但是我认为我可能有语法问题,因为在本机 python 中似乎可以正常工作的代码在 Jinja2 模板中失败。我想要一些关于我可能做错了什么的帮助
在高层次上,代码将使用 aws gather fact 收集的子网列表,使用单独的 yaml 文件中提供的数字来确定要附加到单独列表中的子网数量,以便 for 循环运行,并且填充一个单独的 yaml 文件。
{% set subnets_to_use = [] %}
{% set number_of_subnets = {{ cluster.master }} %} <-- #this value is set in another yaml file
{% set list = usable_kops_subnets %} <-- this has been set by gather facts seperately
{% set list_len = list | length %}
{% for i in range(number_of_subnets) %}
{{ subnets_to_use.append(list[(i)%list_len]) }} <-- #appears to fail here
{% endfor %}
{% for etcd_host_id in subnets_to_use[:cluster.master] %}
- instanceGroup: master-{{ etcd_host_id.availability_zone }}-{{ loop.index }}
name: {{ etcd_host_id.availability_zone }}-{{ loop.index }}
{% endfor %}
"msg": "AnsibleError: 模板化字符串时出现模板错误:预期标记 ':',得到 '}'
当我在 python 编译器中运行类似的 Python 代码时,代码似乎可以工作
例如:
x = 400
list = ["string1","str2","str3","str4"]
subnets_to_use = []
list_len = len(list)
for i in range(x):
subnets_to_use.append(list[(i)%list_len])
print (subnets_to_use)
【问题讨论】:
-
在将
subnets_to_use发送到模板之前,将所有元素附加到subnets_to_use。 -
感谢您的回答 - 您是否建议在模板之外进行设置?
-
这是最自然的方法 - 在将所有需要的数据发送到模板之前创建它们。没有创建模板来替换 Python 的代码。
-
在模板之外这样做有意义吗?
-
Python 的代码应该收集所有数据,然后使用模板显示数据。在模板中混合代码只会像在 PHP 中那样混乱。