Lee Fox
Lee Fox

Reputation: 217

Indexing all but one host in an inventory

I have a playbook that looks something like:

  - name:  Install myApp
    hosts: tag_app_prod[0]
    sudo: yes
    roles:
      - { role: myApp, master: "true" }

Essentially, I have a group of my servers that install the same exact way, except one that I designate as a master server needs a different parameter set. The above works well for that since I can pick the first server in my group and set the parameter and then follow it with the following block to install the rest of the hosts with the alternate setting:

  - name:  Install myApp
    hosts: tag_app_prod[1-25]
    sudo: yes
    roles:
      - { role: myApp, master: "false" }

The problem is that I'm using dynamic inventory, and I won't know how many hosts are going to be in existence at runtime. Is there a way to specify the upper bounds on my host line rather than setting it to a specific number like 25 as I did above?

Upvotes: 2

Views: 973

Answers (1)

Bruce P
Bruce P

Reputation: 20719

Ansible will actually be ok if you use an index above the range of the actual list of servers, so this should work:

- name:  Install myApp
  hosts: tag_app_prod[0]
  sudo: yes
  roles:
    - { role: myApp, master: "true" }

- name:  Install myApp
  hosts: tag_app_prod[1-9999]
  sudo: yes
  roles:
    - { role: myApp, master: "false" }

However there's another way you can do this as well. You can set the master variable dynamically using jinja:

- name:  Install myApp
  hosts: tag_app_prod
  sudo: yes
  roles:
    - { role: myApp, master: "{% if inventory_hostname == groups['tag_app_prod'][0] %}True{% else %}False{% endif %}" }

When that role is invoked for the first host in the tag_app_prod group ( groups['tag_app_prod'][0] ) then the variable master will be set to True. For all the other hosts it will be set to False.

Upvotes: 1

Related Questions