3

Make this task will work the first time:

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

If run it a second time, will get the 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 running this task if it already initialized the database on the server?

Vladimir Botka
  • 5,138
  • 8
  • 20
rawmain
  • 291
  • 1
  • 7
  • 17

2 Answers2

6

Q: "stdout: Data directory is not empty!"

A: 18.2. Creating a Database Cluster says:

initdb will refuse to run if the data directory exists and already contains files; this is to prevent accidentally overwriting an existing installation.

To make the command task idempotent use the parameter creates, e.g.

- name: Initialize the Database
  command: /usr/pgsql-9.6/bin/postgresql96-setup initdb
  args:
    creates: /usr/local/pgsql/data
Vladimir Botka
  • 5,138
  • 8
  • 20
1

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

dmourati
  • 25,540
  • 2
  • 42
  • 72
  • 1
    Thank you. Like this: https://www.reddit.com/r/ansible/comments/7v7tro/is_there_a_way_for_my_shell_task_that_checks_if_a/dtqkd6u/ – rawmain Dec 11 '19 at 07:04