1

Suppose I have a template file, containing, among others, a /24 IP range:

...
podCIDR: 192.168.<x>.0/24
...

Now, using Ansible, I want to render this template, with a running number from 1 to the number of hosts in my inventory, so that each host will have a different range. The first will have 192.168.1.0/24, the second 192.168.2.0/24, etc.

How do I do this?

YoavKlein
  • 2,005
  • 9
  • 38
  • What have you tried so far? Is it failing? Have you revised the documentation of the [template module](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html)? – Carlos Monroy Nieblas Dec 15 '22 at 22:32

1 Answers1

2

Declare the index variable in the group_vars/all and use it to create the network

shell> cat group_vars/all
my_index1: "{{ ansible_play_hosts_all.index(inventory_hostname) + 1 }}"
podCIDR: "192.168.{{ my_index1 }}.0/24"

Then, given the inventory

shell> cat hosts
host_1
host_2
host_3

the playbook below

shell> cat pb.yml
- hosts: all
  tasks:
    - debug:
        var: my_index1
    - debug:
        var: podCIDR

gives abridged

TASK [debug] *********************************************************************************
ok: [host_1] => 
  my_index1: '1'
ok: [host_2] => 
  my_index1: '2'
ok: [host_3] => 
  my_index1: '3'

TASK [debug] *********************************************************************************
ok: [host_1] => 
  podCIDR: 192.168.1.0/24
ok: [host_2] => 
  podCIDR: 192.168.2.0/24
ok: [host_3] => 
  podCIDR: 192.168.3.0/24

See:

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Thanks. One question: does the `inventory_hostname` must be unique across all the inventory, or is it possible to have 2 hosts with the same name in different groups? – YoavKlein Dec 16 '22 at 07:08
  • You're missing: 1) The concept of `inventory_hostname`. See *Special Variables* : *"The inventory name for the ‘current’ host being iterated over in the play*". And 2) [Hosts in multiple groups](https://docs.ansible.com/ansible/latest//inventory_guide/intro_inventory.html#hosts-in-multiple-groups). To answer your question. Yes, inventory_hostname is unique. Yes, it is possible to have 2 hosts with the same name in different groups. – Vladimir Botka Dec 16 '22 at 07:19