--- - name: Install keepalived on 3-node cluster hosts: vm1,vm2,vm3 become: true become_user: root serial: 1 # Ensure tasks are executed one host at a time vars_files: - vars.yaml vars: tailscale_host: "{{ hostvars[inventory_hostname]['tailscale_host'] }}" tasks: # - name: Debug gathered facts # ansible.builtin.debug: # var: ansible_facts # - name: List all network interfaces and their IPs # ansible.builtin.debug: # msg: "{{ item.key }}: {{ item.value.ipv4 | map(attribute='address') | list }}" # with_dict: "{{ ansible_facts['network_interfaces'] }}" # when: ansible_facts['network_interfaces'] is defined # - name: Debug k3s_url_ip # ansible.builtin.debug: # msg: "k3s_url_ip: {{ k3s_url_ip }}" - name: Detect interface with the desired IP range ansible.builtin.set_fact: keepalived_interface: "{{ item.key }}" with_dict: "{{ ansible_facts['network_interfaces'] }}" when: item.value.ipv4 is defined and item.value.ipv4 | selectattr('address', 'search', '^192\\.168\\.56\\.') | list | length > 0 register: detected_interface - name: Set detected interface fact ansible.builtin.set_fact: keepalived_interface: "{{ detected_interface.ansible_facts.keepalived_interface }}" when: detected_interface is defined and detected_interface.ansible_facts is defined - name: Fallback to default interface if no match is found ansible.builtin.set_fact: keepalived_interface: "enp0s8" when: keepalived_interface is not defined - name: Fail if no interface is detected even after fallback ansible.builtin.fail: msg: "No interface with the desired IP range was detected, and fallback to default interface failed." when: keepalived_interface is not defined - name: Install keepalived ansible.builtin.apt: name: keepalived state: present - name: Configure keepalived on each node with decremented priority ansible.builtin.copy: dest: /etc/keepalived/keepalived.conf content: | vrrp_instance VI_1 { state MASTER interface {{ keepalived_interface }} virtual_router_id 51 priority {{ 100 - (groups['vms'].index(inventory_hostname)) }} advert_int 1 authentication { auth_type PASS auth_pass mysecret } virtual_ipaddress { {{ k3s_url_ip }} } } owner: root group: root mode: "0644" - name: Enable and restart keepalived service ansible.builtin.systemd: name: keepalived enabled: true state: restarted