Using with_items with a dictionary

Hello,

I have a dict that contains a list of sites. For each of these sites I would like to provide a list of symlinks to create provided by with_items. Is this possible? I have Ansible 2.3.1.0.

Thanks!
Michael

I'm not quiet sure I understand your data model but instead of with_items have a look at with_dict.

Thanks for responding Uwe! I appreciate your time. :slight_smile:

I’m already using a with_dict to get the list of sites, but now for each site I would like to provide a list of symlinks to generate. The list of symlinks does not change.

This creates the docroots:

  • name: Create docroot
    file: path=/var/www/html/{{ item.value.url }} state=directory owner=www-data group=www-data
    with_dict: “{{ sites }}”
    when: item.value.type == “grav”
    tags: grav, grav-sites

I would like to create the same symlinks for each of these sites, but I don’t know how to get {{ site from dict }}:

  • name: Create symlinks
    file: dest=/var/www/html/{{ site from dict }}/{{ item }} src=/var/www/grav/grav/{{ item }} state=link owner=www-data group=www-data
    with_items:
  • bin
  • CHANGELOG.md
  • composer.json
  • .editorconfig
  • .gitignore
  • index.php
  • LICENSE.txt
  • system
  • vendor
    tags: grav, grav-sites

My first thought was to put those two tasks into a block, modify task 1 to register a new variable that contains the current site
and use it in task 2. Then I remembered that you cannot loop over a block (currently…
https://github.com/ansible/ansible/issues/13262).

You could try to create a new list variable out of your dict which only contains all {{ site from dict }} and then use
with_nested. E.g.

- name: 'create docroot'
  ...

- name: 'extract sites'
  set_fact: sitenames='{{ sitenames | default() }} + {{ item.name }}'
  with_dict: '{{ sites }}'

- name: 'create symlinks'
  file:
    dest: '/var/www/html/{{ item[0] }}/{{ item[1] }}'
    src: '/var/www/grav/grav/{{ item[1] }}'
    state: link
    owner: www-data
    group: www-data
  with_nested:
    - '{{ sitenames }}'
    - [ 'bin', 'CHANGELOG.md', ...]

Hi Michael, This simple example might help you that how we can use the with_items with dictionary:

`