Kevin C
Kevin C

Reputation: 5750

How can I index the number of hosts in play based on a variable?

I want to set a fact, so that all my hosts to know the index number of a certain host in a play, based on a defined variable. I am creating a role, so the order of the hosts can change each run.

Imagine there are 3 hosts in the play. Let's say host-2 has variable me set to true, while the others have it set to false.

host-1 # variable 'me' is false
host-2 # variable 'me' is true, index number is 1
host-3 # variable 'me' is false

Now, imagine the play is sorted like this:

host-3 # variable 'me' is false
host-1 # variable 'me' is false
host-2 # variable 'me' is true, index number is 2

In this case, I want all hosts have a fact which contains the index number of the host in the play. Example: the_index_host: 2, because that is the host with the defined variable.

So far, I know how to configure Ansible to fact share amongst hosts, but got no clue how set a fact based on index number, based on a value.

- block:

    - name: create dict of variable me amongst hosts
      set_fact:
        something: "{{ dict(keys|zip(values)) }}"
      vars:
        keys: "{{ ansible_play_hosts }}"
        values: "{{ ansible_play_hosts |
                    map('extract', hostvars, ['me'])
                    | list }}"

    - name: set_fact for index number
      set_fact:
        the_index_host: "{{ something }}"

  run_once: true

Upvotes: 1

Views: 569

Answers (1)

larsks
larsks

Reputation: 312038

If you wanted the host name instead of the index, you could do this:

- set_fact:
    primary_host: "{{ item }}"
  when: hostvars[item].me|default(false)
  loop: "{{ ansible_play_hosts }}"

I guess if you wanted the index, that would be:

- set_fact:
    primary_host: "{{ hostidx }}"
  when: hostvars[item].me|default(false)
  loop: "{{ ansible_play_hosts }}"
  loop_control:
    index_var: hostidx

Upvotes: 3

Related Questions