Search code examples
ansibleansible-inventory

reverse inventory order on demand


I have a playbook that I have been using for a while. The playbook defines certain parameters and variables for an East and a West location. West has always been the primary location and East the backup. We are now switching the logic to where the customer is located, that will be the Primary location. I am trying to reverse the inventory hosts when the location is on the East Coast that way the East Coast equipment will get the primary setup then the West Coast. I have tried the following without any luck. According to the documentation this is the correct syntax for reversing the order of the inventory file.

The offending line appears to be:

when: location == "east" order: reverse_inventory ^ here

- hosts: cisco_lab
  when: location == "east"
    order: reverse_inventory

  ......Rest of playbook

Solution

  • Use ternary, e.g. given the inventory

    shell> cat hosts
    [cisco_lab]
    host1
    host2
    host3
    

    The playbook

    shell> cat playbook.yml
    ---
    - hosts: cisco_lab
      order: "{{ (location == 'east')|ternary('reverse_inventory', 'inventory') }}"
      gather_facts: false
      tasks:
        - debug:
            var: inventory_hostname
    

    executes the east location in reverse order

    shell> ansible-playbook -i hosts playbook.yml -e location=east
    
    PLAY [cisco_lab] ***********************************************************
    
    TASK [debug] ***************************************************************
    ok: [host3] => 
      inventory_hostname: host3
    ok: [host2] => 
      inventory_hostname: host2
    ok: [host1] => 
      inventory_hostname: host1