You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:12:02