Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to Loop with with_dict and with_nested together using Ansible Playbook?

I am trying to loop over a hash and arrays associated with it like this:

Var:

  dictionary:
    aword: [ ant, den ]
    bword: [ fat, slim ]

Task:

name: Create symlinks
command: do something with item[0] over item[1]
with_nested:
  - "{{ item.key }}"
  - "{{ item.value }}"
with_dict: dictionary

This does not work. Am I doing something wrong or Ansible doesn't support such iteration?

like image 294
avellable Avatar asked Feb 02 '16 05:02

avellable


2 Answers

I solved this one using

with_subelements

like this

vars:

dictionary:
- name: aword
  words:
    - ant
    - den
- name: bword
  words:
    - fat
    - slim

Task:

name: Create symlinks
command: do something with item.0.name over item.1
with_subelements: 
  - dictionary
  - words
like image 59
avellable Avatar answered Oct 06 '22 17:10

avellable


For completeness, this can also be accomplished using with_nested by creating nested lists in Ansible. Doing so allows the same looping behavior without requiring setting a var/fact. This is useful for when you want to instantiate the nested lists on the task itself.

Like so:

---

- hosts: localhost
  connection: local
  become: false

  tasks:

    - debug:
        msg: "do something with {{ item[0] }} over {{ item[1] }}"
      with_nested:
        - - ant  # note the two hyphens to create a list of lists
          - den

        - - fat
          - slim

Output:

TASK [debug] ********************************************************************************************
ok: [localhost] => (item=[u'ant', u'fat']) => {
    "changed": false,
    "item": [
        "ant",
        "fat"
    ],
    "msg": "do something with ant over fat"
}
ok: [localhost] => (item=[u'ant', u'slim']) => {
    "changed": false,
    "item": [
        "ant",
        "slim"
    ],
    "msg": "do something with ant over slim"
}
ok: [localhost] => (item=[u'den', u'fat']) => {
    "changed": false,
    "item": [
        "den",
        "fat"
    ],
    "msg": "do something with den over fat"
}
ok: [localhost] => (item=[u'den', u'slim']) => {
    "changed": false,
    "item": [
        "den",
        "slim"
    ],
    "msg": "do something with den over slim"
}
like image 33
Ryan Fisher Avatar answered Oct 06 '22 18:10

Ryan Fisher