55

How can I add a user to extra groups in ansible? I don't want to existing set of groups to be replaced, only add the user to the sudo group.

48

According to the User module you can use this:

- name: Adding user {{ user }}  
  user: name={{ user }}
        group={{ user }}
        shell=/bin/bash
        password=${password}
        groups=sudo
        append=yes

You can just add the groups=groupname and append=yes to add them to an existing user when you're creating them

  • 2
    Thanks, the append=yes is indeed what I'm looking for! – vdboor Oct 26 '13 at 9:21
  • 1
    There seems to be an issue with this : what if the user already exists and I just want to add or remove them from a group ? I'm not 100% sure but I think that the "group" attribute is considered only when creating the user. – jlecour Jul 19 '16 at 15:41
  • 2
    I really have an issue with this being the accepted answer, as the question does not state "create a user and add it to a specific group". If we come from a Google search because of the question's title, we'd most likely want to add an existing user to a group. – Daniel F Aug 27 '18 at 11:06
69

If {{ user }} already exists in the system, you should use the following to just add it to a group:

- name: adding existing user '{{ user }}' to group sudo
  user:
    name: '{{ user }}'
    groups: sudo
    append: yes

To add it to a set of groups, you can use a comma separated list, for example groups: admin,sudo.

Just beware that if you omit append: yes, your user will be removed from all other groups, according to the usermod man page. That would useful if you want to use a specific list of groups a user should belong to.

  • 11
    …and beware not to write group: without the s, as this will change the primary GID. – Serge Stroobandt Jun 15 '17 at 20:01
  • ... and beware that if the user does not exist it will will be created! – EM0 Jan 24 at 14:03
  • @EM0 Yes, the user module is supposed to create users if they don't exist, however, the user should review his code if he is trying to modify users that are not even supposed to exist. – Teresa e Junior Jan 24 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.