---
- name: Install Grafana Enterprise repository
  become: true
  ansible.builtin.copy:
    src: grafana.repo
    dest: /etc/yum.repos.d/grafana.repo
    owner: root
    group: "{{ ansible_user }}"
    mode: 0644
  register: _grafana_repo

- name: Install Grafana repository GPG key
  become: true
  ansible.builtin.rpm_key:
    state: present
    key: https://packages.grafana.com/gpg.key

- name: Install Grafana
  become: true
  ansible.builtin.dnf:
    name: grafana
    state: present
    update_cache: "{{ _grafana_repo.changed }}"

- name: Enable and start Grafana
  become: true
  ansible.builtin.systemd:
    name: grafana-server
    state: started
    enabled: true

- name: Fetch installed grafana plugins
  become: true
  ansible.builtin.command:
    cmd: grafana-cli plugins ls
  changed_when: false
  register: _grafana_plugins_raw

- name: Install plugins
  become: true
  ansible.builtin.command:
    cmd: grafana-cli plugins install {{ item }}
  changed_when: item not in _grafana_plugins_raw.stdout
  notify: [restart-grafana]
  loop:
    - marcusolsson-json-datasource
    - grafana-clock-panel
    - ayoungprogrammer-finance-datasource
