---
# Hilfsfunktion zum auslesen lokal gespeicherter Secrets auf dem Server 
# Die Secrets sind aus dem Server jeweils in einer Datei gespeichert 
# Zum Auslesen wird die Datei über Slurp geladen und in einer Variable entsprechend dem 
# Dateinamen registriert.
# Falls die Datei noch nicht existiert wird das Secret entsprechend der vorgegebenen 
# Länge initialisiert 
# 
# Beispiel: (Auslesen von Passörtern aus /srv/xyz/secret_pw, registrierung als Variable secret_pw, erzeugung mit 24 Zeichen falls nicht vorhanden)
# 
# - include: ../functions/get_secret.yml
#   with_items:
#     - { path: /srv/xyz/secret_pw,  length: 24 }
#     - { path: /srv/xyz/secret2_pw, length: 12 }

# Check if file exists  
- name: "{{ item.path | basename }} (check directory)"
  file: 
    path: "{{ item.path | dirname }}"
    state: "directory"

# Check if file exists  
- name: "{{ item.path | basename }} (check file)"
  stat:
    path: "{{ item.path }}" 
  register: filestat 

# Generate secret if missing 
- name: "{{ item.path | basename }} (generate: install openssl)" 
  apt:
    pkg: openssl
    update_cache: no
    state: present
  when: filestat.stat.exists == False 

- name: "{{ item.path | basename }} (generate: length = {{ item.length }})"
  command: "openssl rand -base64 -out {{ item.path }} {{ item.length }}" 
  when: filestat.stat.exists == False 

# Get Secret 
- name: "{{ item.path | basename }} (slurp)"
  slurp: src={{ item.path }}
  register: secretfile

# Decode Secret and register fact 
- name: "{{ item.path | basename }} (decode)"
  set_fact: 
    "{{ item.path | basename }}": "{{ secretfile.content | b64decode | regex_replace('\\s', '') }}"