Create user if not exist in Ansible

ansible

I want to make sure a given user always exist in a system, so only create when it is not exist

my current tasks is:

- name: Create default user
action: user name={{ user }} groups={{ group }}  state=present

However, it raise the error when a user already exists, so how to avoid the error when the user account already exist?

Best Answer

Modules, and therefore, playbooks like the one you show, have to be idempotent to be of any use.

Repeating the same action several times both with a playbook and a onliner does not result in any errors, as expected:

$ ansible 10.0.0.2 -u dawud -m user -a "name=sysadm group=1000 state=present"
10.0.0.2 | success >> {
    "append": false,
    "changed": false,
    "comment": "System Administrator,,,",
    "group": 1000,
    "home": "/home/sysadm",
    "name": "sysadm",
    "shell": "/bin/bash-static",
    "state": "present",
    "uid": 1000
}


$ ansible-playbook ansible/sample.yml -u dawud -K
sudo password:

PLAY [10.0.0.2] *********************

GATHERING FACTS *********************
ok: [10.0.0.2]

TASK: [create admin user] *********************
ok: [10.0.0.2]

PLAY RECAP *********************
10.0.0.2                       : ok=2    changed=0    unreachable=0    failed=0

The playbook I have used:

$ cat ansible/sample.yml
- hosts: 10.0.0.2
  sudo: yes

  tasks:

    - name: create admin user
      action: user name=sysadm group=1000 state=present
Related Topic