Adding A User To An Additional Group Using Ansible


Answer :

Solution 1:

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.

Solution 2:

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


Solution 3:

Please note that {{ user }} was changed to {{ ansible_user }} in recent Ansible versions (https://github.com/ansible/ansible/blob/c600ab81ee/lib/ansible/playbook/play_context.py#L46-L55). Alternatively, you can also use ansible_ssh_user - it's the same. So, the updated code from Teresa e Junior looks like:

- name: adding existing user "{{ ansible_user }}" to group sudo user: name: "{{ ansible_user }}" groups: sudo append: yes become: yes

More fixes:

  • Use double quotes so the variable expands
  • Add become: yes since it needs administrative privileges to change the groups file

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?