Create user if not exist in Ansible
Solution 1:
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