---
- name: "handle secret {{ ansible_hostname }}/minio_{{ minio_user }}_ldappass"
  block:
    - name: "get {{ ansible_hostname }}/minio_{{ minio_user }}_ldappass from hashicorp vault"
      ansible.builtin.set_fact:
        "minio_{{ minio_user | replace('-', '_') }}_ldappass": "{{ lookup('hashi_vault', 'secret=talas-kv/data/' + host_vars_location + '/' + ansible_hostname)['minio_' + minio_user + '_ldappass'] }}"
  rescue:
    - name: "generate a random password for {{ ansible_hostname }}/minio_{{ minio_user }}_ldappass"
      ansible.builtin.set_fact:
        password: "{{ lookup('password','/dev/null chars=ascii_letters,digits length=50') }}"
    - name: "patching hashicorp vault with generated minio_{{ minio_user }}_ldappass"
      ansible.builtin.command: "vault kv patch talas-kv/{{ host_vars_location }}/{{ ansible_hostname }} minio_{{ minio_user }}_ldappass={{ password }}"
      delegate_to: localhost
      become: false
      register: result
      ignore_errors: true
    - name: "patch failed because the entry doesn't exist, creating it instead"
      ansible.builtin.command: "vault kv put talas-kv/{{ host_vars_location }}/{{ ansible_hostname }} minio_{{ minio_user }}_ldappass={{ password }}"
      delegate_to: localhost
      become: false
      when:
        - result.failed
        - '"No value found" in result.stderr'
    - name: "assign password value to minio_{{ minio_user }}_ldappass"
      set_fact:
        "minio_{{ minio_user | replace('-', '_') }}_ldappass": "{{ password }}"
