--- - name: Configure Keepalived for HA Proxy hosts: proxy become: true vars: vip_address: "172.16.1.253" vip_cidr: "23" vrrp_instance: "VI_1" vrrp_id: 51 auth_pass: "ansible_secure_pass" check_script: "/usr/local/bin/check_haproxy.sh" master_priority: 150 backup_priority: 100 tasks: - name: Install keepalived package ansible.builtin.apt: name: keepalived state: present update_cache: true tags: keepalived - name: Create check_haproxy script directory ansible.builtin.file: path: /usr/local/bin state: directory mode: '0755' tags: keepalived - name: Deploy HAProxy health check script ansible.builtin.copy: content: | #!/bin/bash # Check if haproxy is running and listening if pgrep -x "haproxy" > /dev/null; then if ss -tlnp | grep -q ":80 "; then exit 0 fi fi exit 1 dest: "{{ check_script }}" mode: '0755' owner: root group: root tags: keepalived - name: Configure keepalived.conf ansible.builtin.template: content: | global_defs { router_id {{ inventory_hostname }} script_user root enable_script_security } vrrp_script check_haproxy { script "{{ check_script }}" interval 2 weight -20 fall 3 rise 2 } vrrp_instance {{ vrrp_instance }} { state {% if inventory_hostname == 'ha1-cod' %}MASTER{% else %}BACKUP{% endif %} interface eth0 virtual_router_id {{ vrrp_id }} priority {% if inventory_hostname == 'ha1-cod' %}{{ master_priority }}{% else %}{{ backup_priority }}{% endif %} advert_int 1 authentication { auth_type PASS auth_pass {{ auth_pass }} } track_script { check_haproxy } virtual_ipaddress { {{ vip_address }}/{{ vip_cidr }} dev eth0 } } dest: /etc/keepalived/keepalived.conf mode: '0644' backup: true notify: Restart keepalived tags: keepalived - name: Enable and start keepalived service ansible.builtin.systemd: name: keepalived enabled: true state: started daemon_reload: true tags: keepalived handlers: - name: Restart keepalived ansible.builtin.systemd: name: keepalived state: restarted daemon_reload: true