如何使用Ansible遍历嵌套的dict结构? [英] How to traverse a nested dict structure with Ansible?
问题描述
我在一个有趣的剧本中有以下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
:
- 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屋!