---
- name: Install Heartbeat
  hosts: utility_all
  become: true
  vars:
    haproxy_ssl: false

  vars_files:
    - vars/variables.yml

  pre_tasks:
    - include_tasks: common_task_install_elk_repo.yml

    - name: Ensure heartbeat is installed
      apt:
        name: "heartbeat-elastic"
        state: "{{ elk_package_state | default('present') }}"
        update_cache: true
      tags:
        - package_install

    - name: exit playbook after uninstall
      meta: end_play
      when:
        - elk_package_state | default('present') == 'absent'

  post_tasks:
    - name: Drop heartbeat conf file
      template:
        src: templates/heartbeat.yml.j2
        dest: /etc/heartbeat/heartbeat.yml

    - name: Enable and restart heartbeat
      systemd:
        name: "heartbeat-elastic"
        enabled: true
        state: restarted


- name: Load Heartbeat Dashboards
  hosts: utility_all[0]
  become: true
  vars_files:
    - vars/variables.yml
  tasks:
    - name: Load templates
      shell: >-
        {% set IP_ARR=[] %}
        {% for host in groups['elastic-logstash'] %}
        {%   set _ = IP_ARR.insert(loop.index, ((hostvars[host]['ansible_host'] | string) + ":" + (elastic_port | string))) %}
        {% endfor %}
        heartbeat setup
        {{ item }}
        -E 'output.logstash.enabled=false'
        -E 'output.elasticsearch.hosts={{ IP_ARR | to_json }}'
        -e -v
      with_items:
        - "--template"
        - "--dashboards"
      register: templates
      until: templates is success
      retries: 3
      delay: 2
  tags:
    - beat-setup