Loop_control index_var in Ansible 2.0



我有一个与Ansible 2.6兼容的剧本。这个剧本使用loop_control模块来构造一个字符串。

vars:
app_config:
attr1    :
- "1"
nexatt  :
- "b"
...
- set_fact:
app_properties: ""
- name: Reading the Specific Configuration
set_fact:
app_properties: "{{ app_properties }}{{ (index > 0)|ternary(',','') }}{{ item.key }}={{ item.value[0] }}"
loop: "{{  app_config|dict2items }}"
loop_control:
index_var: index

然后将字符串作为选项传递给脚本:

- name: Create Configurations
command: "{{ dir }}/{{ script }}
{{ item }}"
with_items:
- "{{ app_properties }}"

有没有一种方法可以做到这一点,使其与Ansible 2.0兼容(假设Ansible 3.0没有loop_control(?(我有另一个需要Ansible 2.0的设置,需要这个剧本。我无法升级到Ansible 2.6(。

如果您想要一个直接等价的,可以使用with_indexed_items循环构造来迭代列表和索引值。因为with_*循环对它们的输入执行隐含的扁平化,所以您需要将列表包装在列表中,这样最终的剧本看起来是这样的:

- hosts: localhost
gather_facts: false
vars:
app_config:
attr1:
- "1"
nexatt:
- "b"
tasks:
- name: Reading the Specific Configuration
set_fact:
app_properties: "{{ app_properties|default('') }}{{ (item.0 > 0)|ternary(',','') }}{{ item.1.0 }}={{ item.1.1.0 }}"
with_indexed_items: ["{{ app_config.items() }}"]
- debug:
var: app_properties

我放弃了您初始化app_properties的任务,转而支持使用Ansible的CCD_ 5滤波器。

对于你正在做的事情,你甚至不需要使用循环指数例如,如果你愿意与其他人一起生活set_fact任务,你可以这样做:

- hosts: localhost
gather_facts: false
vars:
app_config:
attr1:
- "1"
nexatt:
- "b"
tasks:
- name: Reading the Specific Configuration
set_fact:
app_properties_list: "{{ app_properties_list|default([]) + ['%s=%s' % (item.0, item.1.0)] }}"
with_items: ["{{ app_config.items() }}"]
- name: Create comma-delimieted app_properties list
set_fact:
app_properties: "{{ ','.join(app_properties_list) }}"
- debug:
var: app_properties

以上内容将适用于Ansible 2.0.0.2或更高版本(可能早些时候!(。可能还有其他方法可以解决这个问题以及(例如模板{% for %}...{% endfor %}循环(。

最新更新