- name: Lookup template
  debug:
    msg: "{{ lookup('template', './manifest_grafana.j2') | from_yaml }}"

- name: Set default Grafana manifest
  set_fact:
    grafana_manifest: "{{ lookup('template', './manifest_grafana.j2') | from_yaml }}"
  when: grafana_manifest is not defined

- name: Create an instance of Grafana
  k8s:
    state: '{{ "present" if servicetelemetry_vars.graphing.enabled else "absent" }}'
    definition:
      '{{ grafana_manifest }}'
  when: servicetelemetry_vars.graphing.enabled

# Lookup existing datasources
- block:

  - block:
    - name: Retrieve elastic search secret
      k8s_info:
        api_version: v1
        kind: Secret
        name: elasticsearch-es-elastic-user
        namespace: '{{ meta.namespace }}'
      register: es_secret

    - name: Decode elasticsearch password
      set_fact:
        elasticsearch_pass: '{{ es_secret.resources[0].data.elastic | b64decode }}'
    when: servicetelemetry_vars.backends.events.elasticsearch.enabled

  - name: Remove legacy datasources
    k8s:
      api_version: integreatly.org/v1alpha1
      name: '{{ meta.name }}-ds-prometheus'
      kind: GrafanaDataSource
      namespace: '{{ meta.namespace }}'
      state: absent

  - name: Set datasources
    set_fact:
      ds_manifest: "{{ lookup('template', './manifest_grafana_ds.j2') | from_yaml }}"
    when: ds_manifest is not defined

  - name: Create the datasources
    k8s:
      state: '{{ "present" if servicetelemetry_vars.graphing.enabled else "absent" }}'
      definition:
        '{{ ds_manifest }}'
  when: servicetelemetry_vars.graphing.enabled
