AnsibleUndefinedVariable:'ansible.vars.hostvars.HostVarsVars 对象'没有属性

Lua*_*ira 12 linux ansible

我正在使用 Ansible,在运行我的 playbook 后收到此错误。

这是我的剧本:


---
- name: Set 192.168.122.4 Hostname
  hosts: 192.168.122.4
  gather_facts: false
  become: true
  tasks:
    - name : Name 4
      hostname:
        name:  ansible1.example.com

- name: Set 192.168.122.5 Hostname
  hosts: 192.168.122.5
  gather_facts: false
  become: true
  tasks:
    - name : Name 5
      hostname:
        name: ansible2.example.com

- name: Manage Hosts File
  hosts: all
  gather_facts: true
  become: true
  tasks:
    
    - name: Deploy Hosts Template
      template:
        src: hosts.j2
        dest: /etc/hosts

Run Code Online (Sandbox Code Playgroud)

这是我的模板


# Managed by Ansible
127.0.0.1 localhost
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_default_ipv4']['address'] }} {{ hostvars[host]['ansible_fqdn'] }} {{ hostvars[host]['ansible_hostname'] }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_default_ipv4

我尝试使用调试模块来查看是否收到来自 的响应ansible_default_ipv4,并且我得到了一个列表,其中包括地址,这就是我想要的。因此,远程服务器并不是没有该设置,而是有,信息就在那里,但我如何检索它以便可以填充此/etc/hosts文件。

但我发现这与本身无关ansible_default_ipv4,因为它会给另一个对象带来相同的错误。

所以我猜测这与模板中的这些神奇变量有关。

我的参考资料是:

RHCE 8 - Ansible RHCE - 使用 Jinja 模板填充主机文件 by theurbanpenguin 在 YouTube 上,查找它

Lua*_*ira 9

谢谢@Jack @Zeitounator,问题出在我的库存上。显然,如果您在库存中留下了一台您没有使用的服务器,例如,我的库存是

10.0.2.[4:7]

但我把我的 [7] 机器关掉了,一旦我移除并制作了我的库存,就像

10.0.2.[4:6] 它开始工作。

所以我猜测,如果你的库存中列出了一台不再使用的机器,它可能会导致魔法变量出现问题。

我的教训是保持库存文件干净。

谢谢