- hosts: localhost
  become: yes
  become_method: sudo
  roles:
    - role: cloudalchemy.prometheus
      environment:
        http_proxy: "{{PROXY}}"
        https_proxy: "{{PROXY}}"
      vars:
        prometheus_targets:
          node:
          - targets:
            - "{{ansible_hostname}}:9100"
            
    - role: cloudalchemy.grafana
      environment:
        http_proxy: "{{PROXY}}"
        https_proxy: "{{PROXY}}"
      vars:
        grafana_security:
          admin_user: admin
          admin_password: admin
        grafana_datasources:
        - name: prometheus
          type: prometheus
          url: "http://{{ansible_default_ipv4.address}}:9090"
          basicAuth: false
        grafana_dashboards:
        - dashboard_id: 2428
          revision_id: 7
          datasource: prometheus
        - dashboard_id: 11879
          revision_id: 3
          datasource: prometheus
        - dashboard_id: 11074
          revision_id: 9
          datasource: prometheus
  tasks:
    - name: populate service facts
      service_facts:
      
    - name: Open stat port for firewalld
      firewalld:
        port: "{{ item }}/tcp"
        state: enabled
        permanent: yes
        immediate: yes
      ignore_errors: yes
      no_log: True
      debugger: never
      when: (ansible_facts['os_family'] == "RedHat" or ansible_facts['os_family'] == 'CentOS')  and ansible_facts.services["firewalld.service"]['state'] == "running"
      with_items:  [ "3000", "9090" ]

    - name: Open stat port for iptables
      iptables:
        chain: INPUT
        destination_port: "{{ item }}"
        jump: ACCEPT
        protocol: tcp
      ignore_errors: yes
      with_items:  [ "3000", "9090" ]

    - name: Ensure group "grafana" exists
      ansible.builtin.group:
        name: grafana
        state: present

    - name: Add the Grafana user
      user:
        name: grafana
        shell: /sbin/nologin
        groups: grafana
        append: yes

    - name: Create a directory if it does not exist
      file:
        path: "{{ item }}"
        state: directory
        mode: '0755'
        owner: grafana
      with_items:
        - /var/lib/grafana
        - /var/log/grafana
        - /etc/grafana

    - name: Create grafana.ini
      file:
        path: /etc/grafana/grafana.ini
        owner: grafana
        group: grafana
        mode: '0644'
        state: touch

    - name: Restart service Grafana, in all cases
      service:
        name: grafana-server
        state: restarted