Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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  }}"

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }}"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading