---
- name: Promtail
  become: "{{ false if inventory_hostname == 'nas.home.lan' else true }}"
  block:
    - name: Create dir
      ansible.builtin.file:
        path: /etc/apt/keyrings/
        owner: root
        group: root
    - name: Create Banner
      ansible.builtin.shell: wget -q -O - https://apt.grafana.com/gpg.key | gpg --dearmor > /etc/apt/keyrings/grafana.gpg
      register: my_output
      changed_when: my_output.rc != 0
  # - name: < Fetch file that requires authentication.
  #         username/password only available since 2.8, in older versions you need to use url_username/url_password
  #   ansible.builtin.get_url:
  #     url: https://apt.grafana.com/gpg.key
  #     dest: /etc/foo.conf
  #     username: bar
  #     password: '{{ mysecret }}'
  #   changed_when: my_output.rc != 0

    - name: Create Banner
      ansible.builtin.shell: echo "deb [signed-by=/etc/apt/keyrings/grafana.gpg] https://apt.grafana.com stable main" | tee /etc/apt/sources.list.d/grafana.list
      register: my_output
      changed_when: my_output.rc != 0

    - name: Install packages
      ansible.builtin.apt:
        name:
          - promtail
        update_cache: true

    - name: Creating a file with content
      ansible.builtin.copy:
        dest: "/etc/promtail/config.yml"
        owner: root
        group: root
        mode: '0644'
        content: |
          # This minimal config scrape only single log file.
          # Primarily used in rpm/deb packaging where promtail service can be started during system init process.
          # And too much scraping during init process can overload the complete system.
          # https://github.com/grafana/loki/issues/11398

          server:
            http_listen_port: 9080
            grpc_listen_port: 0

          positions:
            filename: /tmp/positions.yaml

          clients:
          - url: http://192.168.77.101:3100/loki/api/v1/push
            external_labels:
                nodename: {{ inventory_hostname }}

          scrape_configs:
          - job_name: system
            static_configs:
            - targets:
                - localhost
              labels:
                job: varlogs1
                #NOTE: Need to be modified to scrape any additional logs of the system.
                __path__: /var/log/zabbix/*.log
            - targets:
                - localhost
              labels:
                job: omv_backup
                __path__: /myapps/omv_backup.log

    - name: Sshd
      ansible.builtin.service:
        name: promtail
        state: restarted
