- name: 1. Check Postgres DB Data
  command: "{{ role_path }}/files/postgres_check_data {{ cmoa_namespace }}"
  register: pg_check_result

- name: 2. Insert Elasticsearch template
  command: "sh {{ role_path }}/files/03-ddl-dml/elasticsearch/es-ddl-put.sh {{ cmoa_namespace }}"
#  when: pg_check_result.stdout != '1'
#  register: es

#- debug:
#    msg: "{{es.stdout_lines}}"

- name: 2.1. Elasticsearch dependency deploy restart
  command: "kubectl -n {{ cmoa_namespace }} rollout restart deploy alertmanager base-cortex-configs base-cortex-distributor base-cortex-ruler"
  register: restart

- debug:
    msg: "{{restart.stdout_lines}}"

- name: 2.2. Check Kubernetes Pods (Elasticsearch dependency)
  command: "{{ role_path }}/files/k8s_status {{ cmoa_namespace }} alertmanage"

- name: 3. Get a list of all pods from the namespace
  command: kubectl -n "{{ cmoa_namespace }}" get pods --no-headers -o custom-columns=":metadata.name"
  register: pod_list
  when: pg_check_result.stdout != '1'

- name: 4. Copy psql file in postgres (DDL) 
  kubernetes.core.k8s_cp:
    namespace: "{{ cmoa_namespace }}"
    pod: "{{ item }}"
    remote_path: /tmp/postgres_insert_ddl.psql
    local_path: "{{ role_path }}/files/03-ddl-dml/postgres/postgres_insert_ddl.psql"
  when: item is match('postgres') and pg_check_result.stdout != '1'
  with_items: "{{ pod_list.stdout_lines }}"
  ignore_errors: true

- name: 5. Execute a command in postgres (DDL)
  kubernetes.core.k8s_exec:
    namespace: "{{ cmoa_namespace }}"
    pod: "{{ item }}"
    command: bash -c "PGPASSWORD='eorbahrhkswp' && /usr/bin/psql -h 'localhost' -U 'admin' -d 'postgresdb' -f /tmp/postgres_insert_ddl.psql"
  with_items: "{{ pod_list.stdout_lines }}"
  when: item is match('postgres')
  ignore_errors: true

- name: 6. Copy psql file in postgres (DML)
  kubernetes.core.k8s_cp:
    namespace: "{{ cmoa_namespace }}"
    pod: "{{ item }}"
    remote_path: /tmp/postgres_insert_dml.psql
    local_path: "{{ role_path }}/files/03-ddl-dml/postgres/postgres_insert_dml.psql"
  with_items: "{{ pod_list.stdout_lines }}"
  when: item is match('postgres')
  ignore_errors: true

- name: 7. Execute a command in postgres (DML)
  kubernetes.core.k8s_exec:
    namespace: "{{ cmoa_namespace }}"
    pod: "{{ item }}"
    command: bash -c "PGPASSWORD='eorbahrhkswp' && /usr/bin/psql -h 'localhost' -U 'admin' -d 'postgresdb' -f /tmp/postgres_insert_dml.psql"
  with_items: "{{ pod_list.stdout_lines }}"
  when: item is match('postgres')
  ignore_errors: true