python - 如何在 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)
解决方案
看起来你专注于错误的路线。更改此行
{% set number_of_subnets = {{ cluster.master }} %}
对此
{% set number_of_subnets = cluster.master %}
然后它应该可以正常工作。
推荐阅读
- java - 如何序列化和反序列化哈希表?
- python - 如何在 Keras 中使用 LSTM 添加 Conv2D 层?
- ag-grid - aggrid:如何在侧边栏过滤器工具面板中设置 ag-virtual-list-item 的行高?
- excel - 我的 If 函数不会被考虑在内
- html - HTML 边框放置
- css - 如何更新 Site.less/site.css 和 bundle/minify 以使用 BuildBundlerMinifier 生成输出
- amazon-web-services - AWS CloudWatch 使用 springboot 记录并禁用服务器本身的日志
- android - 将 onCenter={} 设置添加到 react-native-image-pan-zoom 会触发语法错误
- if-statement - 如何将此公式转换为 ArrayFormula 以便将其应用于列
- javascript - 向对象中的值添加单引号(javascript)