我正在尝试在一些目标计算机中创建配置文件。在本地机器中,我应该为每个主机增量分配一个私有IP。
我愚蠢的大脑认为这很简单,所以我这样做了,但失败得很惨。我认为这是主机之间的变量范围问题。因此,在模板中增加它们是没有帮助的。需要一种方法来使用可以存在于所有主机中的变量,并且可以从模板内递增。
有什么想法吗?
- name: mock Playbook
hosts: all
vars:
counter: 1
tasks:
- name: Template configuration
template:
src: server.j2
dest: /tmp/server.conf
这是我的模板文件(
server.j2
):
Address = {{ '10.0.0.' + counter |string }}
{% set counter = counter + 1 %}
现在,所有主机都在配置文件中分配了相同的 IP,即:
#in the 1st host
cat /tmp/server.conf
Address = 10.0.0.1
#in the 2nd host
cat /tmp/server.conf
Address = 10.0.0.1
#in the 3rd host
cat /tmp/server.conf
Address = 10.0.0.1
我希望有这样的事情:
#in the 1st host
cat /tmp/server.conf
Address = 10.0.0.1
#in the 2nd host
cat /tmp/server.conf
Address = 10.0.0.2
#in the 3rd host
cat /tmp/server.conf
Address = 10.0.0.3
库存文件:
all:
children:
server:
hosts:
vm1:
ansible_host: 192.168.122.173
ansible_user: ansibleprime
ansible_ssh_private_key_file: /home/ansibleprime/.ssh/id_ed25519
client:
hosts:
vm2:
ansible_host: 192.168.122.87
ansible_user: ansibleprime
ansible_ssh_private_key_file: /home/ansibleprime/.ssh/id_ed25519
vm3:
ansible_host: 192.168.122.233
ansible_user: ansibleprime
ansible_ssh_private_key_file: /home/ansibleprime/.ssh/id_ed25519
以下解决方案对我有用。 :
Address = {{ '10.0.0.' + (groups['all'].index(inventory_hostname) +1) |string }}
感谢这个答案。