Ansible:是否可以将字典列表添加到数组中?
Ansible: Is it possible do add a list of dictionaries to an array?
我的任务是创建一个字典列表,我需要对其进行迭代,并将元素添加到另一个列表 - 有效地创建一个“字典列表列表”。
到目前为止,我已经在 Ansible 角色中生成了以下代码:
角色
- name: "Iteration"
set_fact:
pool_members:
- name: "{{ item | split('.') | first }}"
host: "{{ lookup( 'community.general.dig' , item) }}" # This just resolves the FQDN of the iterated item and adds the IP address as a value
port: "{{pool_member_port | int}}"
with_items:
- "{{ groups['needed_hosts'] }}"
when:
- condition == False
剧本只调用角色,不修改变量:当我只调用pool_members
事实时,我只得到组的最后一项。
我想了解是否可以将这些项目添加到数组中,以便 pool_members
事实包含主机的所有定义,如下所示:
[
- "name": "host-1.test.local"
"host": "192.168.1.1"
"port": "12345"
- "name": "host-2.test.local"
"host": "192.168.1.2"
"port": "12345"
- "name": "host-3.test.local"
"host": "192.168.1.3"
"port": "12345"
]
因此,当我调用它时,我拥有变量中的所有成员。
在此先感谢您提供的任何帮助。
您离结果还差得很远,只需使用临时变量并创建字典即可。
此剧本创建字典列表:
- name: "Iteration"
set_fact:
pool_members: "{{ pool_members | d([]) + [{'name': name, 'host': host, 'port': port}] }}"
vars:
name: "{{ item | split('.') | first }}"
host: "{{ lookup( 'community.general.dig' , item) }}" # This just resolves the FQDN of the iterated item and adds the IP address as a value
port: "{{pool_member_port | int}}"
with_items:
- "{{ groups['needed_hosts'] }}"
when:
- condition == False
过滤器d([])
(或default([])
)表示:如果变量不存在,则将其初始化为[]
我的任务是创建一个字典列表,我需要对其进行迭代,并将元素添加到另一个列表 - 有效地创建一个“字典列表列表”。
到目前为止,我已经在 Ansible 角色中生成了以下代码:
角色
- name: "Iteration"
set_fact:
pool_members:
- name: "{{ item | split('.') | first }}"
host: "{{ lookup( 'community.general.dig' , item) }}" # This just resolves the FQDN of the iterated item and adds the IP address as a value
port: "{{pool_member_port | int}}"
with_items:
- "{{ groups['needed_hosts'] }}"
when:
- condition == False
剧本只调用角色,不修改变量:当我只调用pool_members
事实时,我只得到组的最后一项。
我想了解是否可以将这些项目添加到数组中,以便 pool_members
事实包含主机的所有定义,如下所示:
[
- "name": "host-1.test.local"
"host": "192.168.1.1"
"port": "12345"
- "name": "host-2.test.local"
"host": "192.168.1.2"
"port": "12345"
- "name": "host-3.test.local"
"host": "192.168.1.3"
"port": "12345"
]
因此,当我调用它时,我拥有变量中的所有成员。
在此先感谢您提供的任何帮助。
您离结果还差得很远,只需使用临时变量并创建字典即可。
此剧本创建字典列表:
- name: "Iteration"
set_fact:
pool_members: "{{ pool_members | d([]) + [{'name': name, 'host': host, 'port': port}] }}"
vars:
name: "{{ item | split('.') | first }}"
host: "{{ lookup( 'community.general.dig' , item) }}" # This just resolves the FQDN of the iterated item and adds the IP address as a value
port: "{{pool_member_port | int}}"
with_items:
- "{{ groups['needed_hosts'] }}"
when:
- condition == False
过滤器d([])
(或default([])
)表示:如果变量不存在,则将其初始化为[]