Creating a loop in ansible Play book - Error

Viewed 68

The Play book

---
- name: task 11
  hosts: prod
  vars_files:
    - users_pass.yml
  tasks:
    - name: create group profs
      group:
        name: profs
        state: present

    - name: create users who have depart set as profs
      user:
        name: "{{ item.uname }}"
        groups: "{{ item.department }}"
        shell: /bin/bash
        password: "{{ item.password | password_hash ('sha256') }}"
      when: "'{{ item.department }}'=='profs'"
      loop: " {{ users }} "

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#the users_pass.yml
---
users:
- uname: linda
  password: password
  department: profs

- uname: lisa
  password: secret
  department: profs

- uname: anna
  password: geheim
  department: students

when running the above mentioned playbook and adding this var file i get the following error:

fatal: [ansible5]: FAILED! => {
    "msg": "Invalid data passed to 'loop', it requires a list, got this instead:  [{'uname': 'linda', 'password': 'password', 'department': 'profs'}, {'uname': 'lisa', 'password': 'secret', 'department': 'profs'}, {'uname': 'anna', 'password': 'geheim', 'department': 'students'}] . 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."
}

I really don't understand, I am sure that my declaration of variable is correct. Any help, please?

1 Answers

I think the problem is due to the space within the quotes in variable to loop, i.e. " {{ users }} ". There might be another "hidden" issue in the when condition due to the use of Jinja delimiters {{.

Overall, it should work with changes as below:

    - name: create users who have depart set as profs
      user:
        name: "{{ item.uname }}"
        groups: "{{ item.department }}"
        shell: /bin/bash
        password: "{{ item.password|password_hash('sha256') }}"
      when: item.department == "profs"
      loop: "{{ users }}"
Related