如何在jinja2模板中运行python附加列表

时间:2019-09-03 12:30:41

标签: python ansible jinja2

我正在尝试使用Jinja2中的python进行for循环,该循环将创建并追加到列表中-但是我认为我可能遇到语法问题,因为在Jinja2模板中似乎可以在本机python中正常工作的代码失败。对于我可能做错的事情,我需要一些帮助

在较高级别,代码将使用aws收集事实收集的子网列表,使用单独的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)

2 个答案:

答案 0 :(得分:1)

您似乎在关注错误的行。更改此行

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

对此

{% set number_of_subnets = cluster.master %}

然后应该可以正常工作。

答案 1 :(得分:0)

我最终在ansible中使用以下命令,而不是使用python-似乎可以工作。在这种情况下,clusters.node被定义为3,而我有一个aws收集事实的子网。我想要创建3个实例组,所有实例组都具有相同的子网。

- name: setup of subnet variables on nodes
  hosts: localhost
  gather_facts: false
  vars:
    subnets: "{{usable_kops_subnets}}"
    subnet_length: "{{subnets | length }}"
    servers: "{{cluster.node}}"
    slist_nodes: []
  tasks:
  - name: slist_nodes setup
    set_fact:
       slist_nodes: '{{ slist_nodes + [subnets[(item|int + 0) % (subnet_length|int + 0)]] }}'
    loop: "{{range(0,servers|int,1)| list}}"

然后我针对“ slist_nodes”列表运行循环,例如

{% for subnet in slist_nodes %}

< code>

{% endfor %}

这将使用子网创建3个实例。