如何使用 Ansible 遍历嵌套的 dict 结构? [英] How to traverse a nested dict structure with Ansible?
问题描述
我在 ansible playbook 中有以下 dict 结构变量:
I have the following dict structure variable in an ansible playbook:
apache_vhosts:
- name: foo
server_name: foo.com
server_aliases:
- a.foo.com
- b.foo.com
- c.foo.com
- name: bar
server_name: bar.com
server_aliases:
- d.bar.com
- e.bar.com
- f.bar.com
我需要为每个 server_name
和 server_aliases
域创建一个符号链接,例如:
I need to create a symlink for each of the server_name
and server_aliases
domains, e.g.:
/tmp/foo.com -> /var/www/foo
/tmp/a.foo.com -> /var/www/foo
/tmp/b.foo.com -> /var/www/foo
/tmp/c.foo.com -> /var/www/foo
/tmp/bar.com -> /var/www/bar
/tmp/d.bar.com -> /var/www/bar
/tmp/e.bar.com -> /var/www/bar
/tmp/f.bar.com -> /var/www/bar
我有以下任务适用于 server_name
:
I have the following task which works for the server_name
:
- name: Add a domain symlinks /tmp for server_name.
file:
src: "/var/www/{{ item.name }}"
dest: "/tmp/{{ item.server_name }}"
state: link
with_items: apache_vhosts
但我不确定如何对 server_aliases
数组做同样的事情.
But I'm not sure how I can do the same for the array of server_aliases
.
如有必要,我很乐意使用两个单独的任务,但我很想避免添加一个单独的 domains
变量,该变量在平面结构中复制域列表.
I'm happy to use two separate tasks if necessary, but I'm keen to avoid having to add a separate domains
variable which duplicates the list of domains in a flat structure.
这篇Google 网上论坛帖子很接近,但我可以不知道如何使它适用于多个虚拟主机.
This Google Groups post is close, but I can't work out how to make it work for multiple virtual hosts.
这可能吗?或者这从根本上是错误的方法?
Is this possible? Or is this fundamentally the wrong approach?
推荐答案
您可以使用 with_subelements 循环遍历 server_aliases.下面的片段
You can use with_subelements to loop through the server_aliases. The below snippet
- name: Add a domain symlinks /tmp for server_name.
debug: msg="{{ item.server_name }}"
with_items: apache_vhosts
- name: Add a domain symlinks /tmp for server_aliases.
debug: msg="name - {{ item.0.name }} and serverAlias - {{ item.1 }}"
with_subelements:
- apache_vhosts
- server_aliases
这篇关于如何使用 Ansible 遍历嵌套的 dict 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!