ansible

Extract the last two elements from a list, no matter the length


I have a list of hosts in Ansible, which will always have minimum three elements:

[server]
apollo
boreas
cerus

Using a fact similar to:

- name: Set loadbalancer hosts fact
  ansible.builtin.set_fact:
    loadbalancer_hosts: "{{ groups['server'][1:3] }}"
  run_once: true

Will return the last 2 hosts. However, I want to be able to extract the last two hosts, even if I add additional hosts, later on. For example, if my list of hosts becomes:

[server]
apollo
boreas
cerus
chaos

loadbalancer_hosts should be

 - cerus
 - chaos

Solution

  • See Array slicing. In Ansible, use the Python syntax:

      loadbalancer_hosts: "{{ groups.server[-2:] }}"
    

    Given the inventory

    shell> cat hosts
    [server]
    apollo
    boreas
    cerus
    chaos
    

    gives what you want

      loadbalancer_hosts:
      - cerus
      - chaos
    

    Example of a complete playbook for testing

    - hosts: all
    
      vars:
    
        loadbalancer_hosts: "{{ groups.server[-2:] }}"
    
      tasks:
    
        - debug:
            var: loadbalancer_hosts
          run_once: true