0

I use the following ansible task to set up an MDB database for OpenLDAP:

- name: set up MDB database
  shell: ldapadd -Y EXTERNAL -H ldapi:/// -f {{tmp_dir}}/mdb.ldif

However, once the DB has been setup, if I run the playbook again, I get the error:

<olcSuffix> namingContext "dc=test,dc=cluster" already served by a preceding mdb database

I obviously need to add a when condition, so that the DB is only set up, if it does not already exist. However, I don't know what to test for. Should I add a custom fact based on, say, ldapsearch, or is there a better way?

loris
  • 450
  • 8
  • 20
  • I ended up doing the following, which seems to work for my purposes: - name: test whether MDB database already exists shell: ldapsearch -H ldap:// -x -s base -b "" -LLL "namingContexts" | grep -c "{{ ldap_suffix }}" register: is_db_setup - name: set up MDB database shell: ldapadd -Y EXTERNAL -H ldapi:/// -f {{tmp_dir}}/mdb.ldif when: not is_db_setup.stdout – loris Jan 05 '16 at 14:39
  • You should add this as an answer to the question. Comments don't allow for formatting, so a nicely formatted answer would be much easier to read than the comment. – Bruce P Jan 05 '16 at 20:11

3 Answers3

1

As Bruce P pointed out, I should have answered my own question to allow formatting:

I ended up doing the following, which seems to work for my purposes:

- name: test whether MDB database already exists 
  shell: ldapsearch -H ldap:// -x -s base -b "" -LLL "namingContexts" | grep -c "{{ ldap_suffix }}"
  register: is_db_setup
- name: set up MDB database
  shell: ldapadd -Y EXTERNAL -H ldapi:/// -f {{tmp_dir}}/mdb.ldif
  when: not is_db_setup.stdout 
loris
  • 450
  • 8
  • 20
1

Actually, piping the result of the search through grep (see my other answer) is not such a good idea, because if the string is not found, an error is generated, which then has to be ignored. It seems more elegant to use the string function find in the when clause:

- name: test whether MDB database already exists
  shell: ldapsearch -H ldap:// -x -s base -b "" -LLL "namingContexts"
  register: naming_contexts
- name: set up MDB database
  shell: ldapadd -Y EXTERNAL -H ldapi:/// -f {{tmp_dir}}/mdb.ldif
  when: naming_contexts.stdout.find("{{ ldap_suffix }}") == -1
loris
  • 450
  • 8
  • 20
1

The initial answers by @loris helped me on my way, but I believe the better way of handling this is to look at the rc value returned by ldapsearch, such as:

- name: test whether MDB database already exists
  shell: ldapsearch -H ldap:// -x -s base -b "" -LLL "namingContexts"
  register: naming_contexts
- name: set up MDB database
  shell: ldapadd -Y EXTERNAL -H ldapi:/// -f {{tmp_dir}}/mdb.ldif
  when: naming_contexts.rc == 32

In my particular case, I found out that the "ldap_suffix" was also present in the stdout. RC 32 means "Object not found" in ldap speak, and this is exactly what the original poster was after: "if the object doesn't exist, create it"

zenlord
  • 330
  • 3
  • 15