首页 > 解决方案 > 如何在 jinja2 模板中运行 python 追加列表

问题描述

我正在尝试在 Jinja2 中使用 python 执行一个 for 循环,该循环将创建并附加到一个列表 - 但是我认为我可能有语法问题,因为在本机 python 中似乎可以正常工作的代码在 Jinja2 模板中失败。我想要一些关于我可能做错了什么的帮助

在高层次上,代码将使用 aws collect 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)

标签: pythonansiblejinja2

解决方案


看起来你专注于错误的路线。更改此行

{% set number_of_subnets = {{ cluster.master }} %}

对此

{% set number_of_subnets = cluster.master %}

然后它应该可以正常工作。


推荐阅读