Eva
Eva

Reputation: 593

Ansible loop dict items

I am using ansible 2.9 and trying to use ansible loop instead of with_dict. I am getting below error. I need to pass the values at the task, I can't keep them in variable or load them at the beginning. do I need to switch back to with_dict?

fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected token 'end of print statement', got ':'. String: {{ key:/var/tmp/h vaule:/tmp/h|dict2items  }}"}

 - name: copy module
   copy: 
     src: "{{ item.key }}"
     dest: "{{ item.value}}"
   loop:
     - "{{ key: /var/tmp/a value:/tmp/h |dict2items  }}"
     - "{{ key: /var/tmp/b value:/tmp/z |dict2items  }}"

Upvotes: 1

Views: 646

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68024

You don't need dict2items here. Fix the syntax. For example, test it first

- hosts: localhost
  tasks:
    - debug:
        msg: >-
          src: {{ item.key }}
          dest: {{ item.value}}
      loop:
        - {key: /var/tmp/a, value: /tmp/h}
        - {key: /var/tmp/b, value: /tmp/z}

gives (abridged)

  msg: 'src: /var/tmp/a dest: /tmp/h'
  msg: 'src: /var/tmp/b dest: /tmp/z'

If this is what you want to copy the files

    - name: copy module
      copy: 
        src: "{{ item.key }}"
        dest: "{{ item.value }}"
      loop:
        - {key: /var/tmp/a, value: /tmp/h}
        - {key: /var/tmp/b, value: /tmp/z}

You'd need dict2items if the structure was a dictionary. For example,

dirs:
  /var/tmp/a: /tmp/h
  /var/tmp/b: /tmp/z

Then the task below would give the same result

    - debug:
        msg: >-
          src: {{ item.key }}
          dest: {{ item.value}}
      loop: "{{ dirs|dict2items }}"

Upvotes: 2

Related Questions