---
- name: Add TCP frontend/backend to existing HAProxy config
  hosts: haproxy
  become: yes

  vars:
    haproxy_cfg_path: /etc/haproxy/haproxy.cfg

  tasks:

    - name: Convert backend_ips string to list
      set_fact:
        backend_list: "{{ backend_ips.split(',') }}"

    - name: Build HAProxy TCP block
      set_fact:
        haproxy_tcp_block: |
          frontend custom_tcp_in
              mode tcp
              bind {{ frontend_ip }}:{{ frontend_port }}
              default_backend custom_tcp_backend

          backend custom_tcp_backend
              mode tcp
              balance {{ balance_type }}
{% for ip in backend_list %}
              server backend{{ loop.index }} {{ ip }}:{{ backend_port }} check
{% endfor %}

    - name: Append TCP block to haproxy.cfg
      lineinfile:
        path: "{{ haproxy_cfg_path }}"
        line: "{{ haproxy_tcp_block }}"
        insertafter: EOF

    - name: Restart HAProxy
      systemd:
        name: haproxy
        state: restarted
