Ansible – How to Assign Multiple Existing Users to a New Group

ansibleansible-playbookautomationlinux

I created a new group in OS. Now I want to assign 5 or more existing users to that group using ansible. I believe I could do this for single user.

---
- name: add user to a group
  become: 'yes'
  become_method: sudo
  hosts: all

  tasks:

  - user:
        name: myusername
        groups: new_group
        append: yes
...

I want to assign all users to that group in one go instead of running the script several time with different username each time.

Best Answer

It sounds like you would like to explore with_items.

From the top of my head, it should look like this:

- user:
    name: "{{ item }}"
    groups: my_group
    append: yes
  with_items:
    - johnsmith
    - beckyjones
    - foobar

You can, of course create a separate list of users in a variable, and call with_items: "{{ userlist }}".

Note the indentation: with_items is in the same indentation level as the module name you call.