Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse a nested dict structure with Ansible?

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?

like image 290
tommarshall Avatar asked Jun 16 '15 13:06

tommarshall


1 Answers

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 
like image 120
VSK Avatar answered Oct 14 '22 01:10

VSK