Database – Use ansible initialize postgresql multiple times

ansibledatabase

Make this task will work first time:

- name: Initialize the Database
  command: /usr/pgsql-9.6/bin/postgresql96-setup initdb

If run it second time, will got error:

fatal: [192.168.0.1]: FAILED! => {"changed": true, "cmd": ["/usr/pgsql-9.6/bin/postgresql96-setup", "initdb"], "delta": "0:00:00.017590", "end": "2019-12-11 06:08:49.999631", "msg": "non-zero return code", "rc": 1, "start": "2019-12-11 06:08:49.982041", "stderr": "", "stderr_lines": [], "stdout": "Data directory is not empty!", "stdout_lines": ["Data directory is not empty!"]}

How to avoid to run this task if it initialized database on the server already?

Best Answer

Check to see if the file/directory created by initdb is there first and if not, initdb.

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html