Ansible loop error: "Invalid data passed to 'loop', it requires a list, got this instead

Viewed 9593

I am trying to download the images in the remote sever by executing the below ansible playbook, however I am struck with the following error. Could anyone help me in resolving this issue.

Ansible-playbook:

name: download images from http
hosts: target1
tasks:
  - name: download the images
    get_url:
      url: "{{ item }}"
      dest: /home/ubuntu
    when: ansible_user== 'ubuntu'
    loop: "{{lookup('file', '/home/ubuntu/file.txt')}}"

error:

fatal: [target1]: FAILED! => {"msg": "Invalid data passed to 'loop', it requires a list, got this instead: https://test.s3.eu-central-1.amazonaws.com/gm.mp4\nhttps://test.s3.eu-central-1.amazonaws.com/ge.mp4 Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup."}

file.txt:

https://test.s3.eu-central-1.amazonaws.com/gm.mp4
https://test.s3.eu-central-1.amazonaws.com/ge.mp4
3 Answers

Split the lines

    loop: "{{ lookup('file', '/home/ubuntu/file.txt').split('\n')  }}"

The next option is lines lookup plugin

    with_lines: cat /home/ubuntu/file.txt

I had a similar issue with having one item in an object, getting the exact same error as you. On Ubuntu 20.04 or MacOS Big Sur this wasn't an issue at all. On Ubuntu 18.04 on the other hand it was a different story.

So for the people trying to get it to work you might consider checking your python version. Python 3.6 doesn't support single entry Lists, you need to upgrade to Python 3.8 (for now).

Getting error while parsing the list of dictionary items inside ansible_facts for mounts when using loop.

debug: msg: "{{ item }}" loop: " {{ ansible_facts['mounts'] }} "

Error: al: [localhost]: FAILED! => {"msg": "Invalid data passed to 'loop', it requires a list, got this instead: [{'mount': '/', 'device': '/dev/sda6', 'fstype': 'ext4', 'options': 'rw,relatime,errors=remount-ro', 'size_total': 58788249600, 'size_available': 40204759040, 'block_size': 4096, If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup."}

Tried multiple solutions, finally below code worked, replacing loop with with_items

#Solution: It worked after lots of effort

name: collect disk data 
debug: 
 msg: "{{ item }}" 

#loop: " {{ ansible_facts['mounts'] }} " with_items: " {{ ansible_facts['mounts'] }} "

Related