YoavKlein
YoavKlein

Reputation: 2703

Rendering different template to each host in Ansible

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?

Upvotes: 1

Views: 379

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68074

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:

Upvotes: 2

Related Questions