Vivek
Vivek

Reputation: 13228

How can I get the sequence number of host entry defined in inventory file (Ansible)?

I have an inventory file with two hosts defined as below

[testservers]
xx.xx.xx.106 ansible_ssh_user=johndoe
xx.xx.xx.138 ansible_ssh_user=johndoe
xx.xx.xx.141 ansible_ssh_user=johndoe

I want to use the sequence number of defined hosts inside the tasks. Like for xx.xx.xx.106 I should get the sequence 1, for xx.xx.xx.141 I should get the sequence value as 3 since its the third entry.

How do I get this sequence number of host entry defined in inventory file without defining additional variables?

Upvotes: 1

Views: 941

Answers (2)

Hvisage
Hvisage

Reputation: 264

Here is a yaml inventory example using @techraf's answer:

    fpm:
      vars:
        Offset: 31
      hosts:
        fpm[01:10]-dc1:
            HostUnit: "{{groups['fpm'].index(inventory_hostname) + Offset}}"
            targethost: "prox0{{HostUnit|int % 2 + 1}}-dc1"
            ansible_ssh_host: "10.123.12.{{HostUnit}}"

Upvotes: 0

techraf
techraf

Reputation: 68439

You can use standard Python's index method.

Replace strings with variables below:

debug:
  msg: "{{ groups['testservers'].index('xx.xx.xx.141') + 1 }}"

(+1 because you explicitly asked for a sequence from 1 to 3, but index starts with 0)

Upvotes: 2

Related Questions