要在Ansible中使用循环嵌套字典,可以通过使用with_nested和with_dict循环控制结构来实现。以下是一个示例代码:
- name: Loop through nested dictionary
hosts: localhost
gather_facts: false
vars:
my_dict:
group1:
- server1
- server2
group2:
- server3
- server4
tasks:
- name: Loop through nested dictionary
debug:
msg: "Group: {{ item.0 }} - Server: {{ item.1 }}"
with_nested:
- "{{ my_dict.keys() }}"
- "{{ my_dict }}"
在上面的示例中,我们有一个名为my_dict的嵌套字典,其中包含两个组(group1和group2),每个组中包含一些服务器。with_nested循环结构用于迭代my_dict.keys()和my_dict,并将当前组和服务器作为item.0和item.1传递给debug模块。
运行上述代码将输出以下结果:
TASK [Loop through nested dictionary] ************************************************************************************************************************************
ok: [localhost] => (item=[u'group1', {u'group1': [u'server1', u'server2'], u'group2': [u'server3', u'server4']}]) => {
"msg": "Group: group1 - Server: [u'server1', u'server2']"
}
ok: [localhost] => (item=[u'group2', {u'group1': [u'server1', u'server2'], u'group2': [u'server3', u'server4']}]) => {
"msg": "Group: group2 - Server: [u'server3', u'server4']"
}
注意,with_nested循环结构将返回一个列表,其中每个元素是一个元组,包含当前组和服务器的键值对。因此,在debug模块中,我们可以通过item.0和item.1访问当前组和服务器。