---
# for the "docker_data_user_name", or pick your own
- name: Include dockerhost vars
  include_vars:
    dir: ../../dockerhost/vars

# for the prometheus authentication parameters
- name: Include prometheus vars
  include_vars:
    dir: ../../prometheus/vars

- name: Include grafana vars
  include_vars:
    dir: vars

- name: Ensure grafana directories
  file:
    name: "{{ item }}"
    state: directory
    owner: "{{ docker_data_user_name }}"
    group: "{{ docker_data_user_name }}"
  loop:
    - "{{ grafana_data_directory }}"
    - "{{ grafana_config_directory }}"

- name: Ensure grafana config directories
  file:
    name: "{{ item }}"
    state: directory
    owner: "{{ docker_data_user_name }}"
    group: "{{ docker_data_user_name }}"
  loop:
    - "{{ grafana_config_directory }}/provisioning/access-control"
    - "{{ grafana_config_directory }}/provisioning/dashboards"
    - "{{ grafana_config_directory }}/provisioning/datasources"
    - "{{ grafana_config_directory }}/provisioning/notifiers"
    - "{{ grafana_config_directory }}/provisioning/plugins"

- name: Copy grafana config
  template:
    src: files/grafana.ini
    dest: "{{ grafana_config_directory }}/grafana.ini"
  register: copy_grafana_configuration

- name: Copy grafana datasources
  template:
    src: "files/datasources/{{ item }}"
    dest: "{{ grafana_config_directory }}/provisioning/datasources/{{ item }}"
  loop:
    - loki.yml
  register: copy_grafana_datasources

- name: Ensure grafana container
  docker_container:
    name: grafana
    image: grafana/grafana:8.2.6
    networks:
      - name: internal
    networks_cli_compatible: yes
    volumes:
      - "{{ grafana_data_directory }}:/var/lib/grafana"
      - "{{ grafana_config_directory }}:/etc/grafana"
    user: "{{ docker_data_uid }}:{{ docker_data_uid }}"
    restart_policy: unless-stopped
    restart: "{{ copy_grafana_configuration.changed or copy_grafana_datasources.changed }}"
    labels:
      # Traefik will use these labels to route the service on HTTPS
      traefik.http.middlewares.grafana-prefix.stripprefix.prefixes: "/grafana"
      traefik.http.routers.grafana.rule: "Host(`{{ ansible_host }}`) && PathPrefix(`/grafana`)"
      traefik.http.routers.grafana.entrypoints: "websecure"
      # use Let's Encrypt certificates of course
      traefik.http.routers.grafana.tls.certresolver: letsEncryptResolver
      traefik.http.routers.grafana.tls: "true"
      traefik.http.routers.grafana.middlewares: "grafana-prefix,grafana-compression"
      traefik.http.services.grafana.loadbalancer.server.port: "3000"
      traefik.http.middlewares.grafana-compression.compress: "true"
...
