使用Ansible的Jinja2模板生成hosts文件时主机名重复问题求助
问题解决:Ansible Jinja2模板生成/etc/hosts时主机名错误
问题原因
你的模板里使用了inventory_hostname变量,这个变量代表当前正在执行Playbook的目标节点的主机名,而非循环遍历的host对应的远程节点主机名。因此循环生成每一行时,都会重复写入当前节点的主机名,导致所有IP都对应同一个名字。
修正后的Jinja2模板(hosts.j2)
把模板中的inventory_hostname替换为host(host变量本身就是inventory中定义的远程节点主机名),或者hostvars[host]['inventory_hostname'](效果完全一致):
{# This is the template for the /etc/hosts file #} {% for host in groups['all'] %} {{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }} {{ host }} {% endfor %}
如果需要同时写入主机短名和全限定域名(FQDN),可以扩展模板:
{# This is the template for the /etc/hosts file #} {% for host in groups['all'] %} {{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }} {{ host }} {{ hostvars[host]['ansible_fqdn'] }} {% endfor %}
验证结果
修正后重新执行Playbook,每个节点的/etc/hosts文件会正确匹配IP与对应主机名:
在zoo1节点上:
192.xxx.xxx.xxx zoo1
192.xxx.xxx.xxy zoo2
...
在zoo2节点上:
192.xxx.xxx.xxx zoo1
192.xxx.xxx.xxy zoo2
...
内容的提问来源于stack exchange,提问作者David S
相关产品推荐
相关产品推荐

