Error creating group with ansible sudo/become

MattB asked:

I’m trying to create a gropu with Ansible, which fails but works if I run it as an SSH command.

The Play

- name: Test error creating groups
  hosts: all
  become: yes
  become_method: sudo
  become_user: xdradmin
  tasks:
  - name: Ensure test group exists
    group:
      name: test
      state: present
      gid: 1001

Attempting to create the group fails with error.

$ ansible-playbook -i web, -u xdradmin test.yml 

PLAY [Test error creating groups] ********************************************************************************************

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

TASK [Ensure test group exists] **********************************************************************************************
fatal: [web]: FAILED! => {"changed": false, "msg": "groupadd: Permission denied.\ngroupadd: cannot lock /etc/group; try again later.\n", "name": "test"}

PLAY RECAP *******************************************************************************************************************
web                        : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

However if I do essentially the same thing manually, it works fine.

 ssh [email protected] 'sudo groupadd -g 1001 test && tail -n1 /etc/group'
test:x:1001:

My answer:


You have told ansible to become (sudo in this case) to the user xdradmin, which apparently has no permission to create groups. Most of the time you should become root as this is the administrative user that will do all the tasks that require root privilege. Indeed, it’s what you did with your ssh command: you became root, not xdradmin. Thus the command worked.

Fix your become_user, e.g.:

become_user=root

The become user is different to the user that ansible connects to the remote system as. That is remote_user.

remote_user=xdradmin

With these two changes, ansible will ssh to the system as user xdradmin, then sudo to root and finally run your task.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.