---
#--------------------------------------------------------------#
# Remove Services from HAProxy                      [pg_service]
#--------------------------------------------------------------#
- name: remove local haproxy services
  tags: pg_service
  become: true
  ignore_errors: true
  when: (pg_service_provider|default('')) == '' or (pg_service_provider|default('')) not in groups
  block:

    # remove service definition with pg_cluster are name prefix
    - name: wipe existing postgres haproxy service
      shell: "cd /etc/haproxy; rm -rf {{ pg_cluster }}-*.cfg;"
      args: { executable: /bin/bash }

    # if the check fails on this step, haproxy will not be reloaded
    - name: check haproxy config before reload
      command: /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q

    # even if you perform haproxy reload on junk config, it will not fail
    - name: reload haproxy
      systemd: name=haproxy state=reloaded enabled=yes daemon_reload=yes


#--------------------------------------------------------------#
# Remove Services from Dedicated HAProxy            [pg_service]
#--------------------------------------------------------------#
# remote service is only removed when primary instance is removed!
- name: remove remote haproxy services
  tags: pg_service
  become: true
  ignore_errors: true
  when: (pg_service_provider|default('')) != '' and (pg_service_provider|default('')) in groups and pg_role == 'primary'
  block:

    # remove service definition with pg_cluster are name prefix
    - name: wipe existing postgres haproxy service
      shell: "cd /etc/haproxy; rm -rf {{ pg_cluster }}-*.cfg;"
      args: { executable: /bin/bash }
      delegate_to: "{{ item }}"
      loop: "{{ groups[pg_service_provider] if (pg_service_provider != '' and pg_service_provider in groups) else [] }}"

    # WARNING: if centralized dedicate haproxy is used, it will fail if haproxy config is not valid!!
    # if the check fails on this step, haproxy will not be reloaded
    - name: check haproxy config before reload
      ignore_errors: false
      any_errors_fatal: true
      command: /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
      delegate_to: "{{ item }}"
      loop: "{{ groups[pg_service_provider] if (pg_service_provider != '' and pg_service_provider in groups) else [] }}"

    # even if you perform haproxy reload on junk config, it will not fail
    - name: reload haproxy
      systemd: name=haproxy state=reloaded enabled=yes daemon_reload=yes
      delegate_to: "{{ item }}"
      loop: "{{ groups[pg_service_provider] if (pg_service_provider != '' and pg_service_provider in groups) else [] }}"

...