Creating users & groups with vars - not working

Trying to create users and groups with vars inline…this is not working…what am I missing here?

— # Users and Groups

  • hosts: localhost
    become: yes
    vars:
    groups:
  • devops
  • dbadbmins
  • serveradmins

users:

  • frank

  • joe

  • dave
    tasks:

  • name: Create groups
    group:
    name: “{{ item.groups }}”
    state: present
    with_items: “{{groups}}”
    ignore_errors: yes

  • name: Create users
    user:
    name: “{{ item.user }}”
    state: present
    with_items: “{{users}}”

Output -

PLAY [localhost] *********************************************************************

TASK [Gathering Facts] ***************************************************************
ok: [localhost]

TASK [Create groups] *****************************************************************
fatal: [localhost]: FAILED! => {“failed”: true, “msg”: “the field ‘args’ has an invalid value, which appears to include a variable that is undefined. The error was: ‘ansible.vars.unsafe_proxy.AnsibleUnsafeText object’ has no attribute ‘groups’\n\nThe error appears to have been in ‘/etc/ansible/playbooks/usersgroups.yml’: line 15, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - name: Create groups\n ^ here\n”}
…ignoring

TASK [Create users] ******************************************************************
fatal: [localhost]: FAILED! => {“failed”: true, “msg”: “the field ‘args’ has an invalid value, which appears to include a variable that is undefined. The error was: ‘ansible.vars.unsafe_proxy.AnsibleUnsafeText object’ has no attribute ‘user’\n\nThe error appears to have been in ‘/etc/ansible/playbooks/usersgroups.yml’: line 22, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Create users\n ^ here\n”}
to retry, use: --limit @/etc/ansible/playbooks/usersgroups.retry

You are trying to access item.groups, but there is not item.groups. The groupname is item itself. The same thing for item.user!

Just change item.groups to item and item.user to item

To put Daniel's response into clear example:

  - name: Create groups
      group:
        name: "{{ item }}"
        state: present
      with_items: "{{groups}}"
      ignore_errors: yes

    - name: Create users
      user:
        name: "{{ item }}"
        state: present
      with_items: "{{users}}"

Thanks Brian!

Thanks. It works but only if I swap with_items: “{{groups}}” for with_items: “{{grouplist}}”

and call my vars grouplist also. Something it didnt like about calling those 2 groups

i should have noticed, 'groups' is a reserved var, which has a
dictionary with the inventory groups and the hosts that belong to
them.

No matter what you set, the 'groups' from Ansible will overwrite it.