---
- name: install apt-transport-https
  ansible.builtin.apt:
    force_apt_get: true
    install_recommends: false
    name: apt-transport-https
    state: latest
  register: apt_status
  retries: 60
  until: apt_status is success or ('Failed to lock apt for exclusive operation' not in apt_status.msg and '/var/lib/dpkg/lock' not in apt_status.msg)

- name: install elastic GPG key
  ansible.builtin.apt_key:
    url: https://artifacts.elastic.co/GPG-KEY-elasticsearch
    state: present

- name: install elastic repository
  ansible.builtin.apt_repository:
    repo: deb https://artifacts.elastic.co/packages/7.x/apt stable main

- name: install metricbeat
  ansible.builtin.apt:
    force_apt_get: true
    install_recommends: false
    name: metricbeat
    state: latest
  register: apt_status
  retries: 60
  until: apt_status is success or ('Failed to lock apt for exclusive operation' not in apt_status.msg and '/var/lib/dpkg/lock' not in apt_status.msg)

- name: install metricbeat configuration
  ansible.builtin.template:
    src: metricbeat.yml.j2
    dest: /etc/metricbeat/metricbeat.yml
    mode: "644"
  notify: restart metricbeat

- name: enable metricbeat dashboard
  ansible.builtin.command:
    cmd: metricbeat setup
  changed_when: false
  when: inventory_hostname == groups['mediaserver'][0]

- name: enable sql metricbeat configuration
  ansible.builtin.template:
    src: postgresql.yml.j2
    dest: /etc/metricbeat/modules.d/postgresql.yml
    mode: "644"
  when: "'postgres' in group_names"
  notify: restart metricbeat

- name: enable metricbeat client
  ansible.builtin.systemd:
    name: metricbeat
    enabled: true
    state: started
