How to traverse a nested dict structure with Ansib

2019-03-28 22:48发布

问题:

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

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

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

But I'm not sure how I can do the same for the array of server_aliases.

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.

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?

回答1:

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