Search code examples
ansiblerheluser-accounts

Using Ansible loop to create multiple users: Undefined error


I am using the following ansible code to create multiple unix user accounts

---
- hosts: test
  become: true
  tasks:
      - name: more complex items to add several users
        user:
         name: "{{ item.name }}"
         uid: "{{ item.uid }}"
         groups: "{{ item.groups }}"
         state: present
        with_items: "{{ user_details }}"

I am storing the user information by using a separate a variable file as below

cat /etc/ansible/vars.yml
---

user_details:
     - { name: testuser1, uid: 1002, groups: "admin, logs" }
     - { name: testuser2, uid: 1003, groups: logs: }

To execute above playbook , I tried with both the commands below

sudo ansible-playbook /etc/ansible/userloop.yml -e /etc/ansible/vars.yml
sudo ansible-playbook /etc/ansible/userloop.yml

but both commands are failing with below error

 fatal: [host-003]: FAILED! => {"msg": "'user_details' is undefined"}
 fatal: [host-004]: FAILED! => {"msg": "'user_details' is undefined"}

How to resolve the issue ? I want to maintain a separate variable file to store the user information rather then putting them in the same playbook file .


Solution

  • You are missing @ while passing the vars.yml. Hence, the ansible is not reading the file. Try the below command. It works for me.

    sudo ansible-playbook /etc/ansible/userloop.yml -e @/etc/ansible/vars.yml