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

Ansible使用hostvars跨主机调用变量报Undefined Variable错误如何解决

问题根本原因

你收到的hostvars['windowsDA'] is undefined错误核心原因是:Ansible的全局主机变量字典hostvars仅会收录当前执行流程中已被命中、且成功完成至少一个任务的主机,只要windowsDA没有被第一个play正常执行任务,就不会出现在hostvars中。

解决步骤

第一步:验证主机可访问性

首先确认你的Ansible主机清单(inventory)中已配置windowsDA的正确WinRM连接参数,执行以下命令验证连通性:

ansible windowsDA -m win_ping

如果返回失败,先修复主机连接配置,确保第一个play可以正常在windowsDA上运行所有任务。

第二步:调整变量调用位置

不要将跨play的hostvars调用写在第二个play的play级vars字段中,部分Ansible版本会在剧本预解析阶段提前解析play级变量,此时第一个play的set_fact任务尚未执行,会触发未定义错误。直接在task中调用变量即可。

修改后可用的playbook示例

- name: Make AD User
  hosts: windowsDA
  # 若不需要采集主机信息可设置为no,不影响set_fact生效
  gather_facts: no

  tasks:
    - name: Set variables as fact
      set_fact:
        var_random_string: "{{ lookup('community.general.random_string', length=3, special=false, base64=false) }}"
        var_name: Pieter
        var_lastname: Post
        var_department: IT
        var_underscore: _

    - name: Create User
      community.windows.win_domain_user:
        enabled: yes
        name: "{{var_name+var_lastname+var_underscore+var_random_string}}"
        firstname: "{{ var_name }}"
        surname: "{{ var_lastname }}"
        company: Poliforma
        password: P@ssw0rd
        password_expired: yes
        path: OU={{var_department}},DC=poliforma,DC=com
        state: present
        description: Werknemer van {{var_department}}Afdeling
        upn: "{{var_name+var_lastname+var_underscore+var_random_string}}@poliforma.com"
        user_cannot_change_password: no
        attributes:
          department: "{{var_department}}Afdeling"

- name: Clone the template and customize
  hosts: localhost
  gather_facts: no

  tasks:
  - name: giveinfo
    debug: 
      msg: "{{ hostvars['windowsDA']['var_name'] }}"

备选稳妥方案(避免依赖windowsDA的hostvars)

如果后续存在windowsDA执行完成后断连、或主机清单动态变化的场景,可以在第一个play中新增变量同步任务,把需要复用的变量同步到localhost的事实变量中,后续直接调用localhost的变量即可:
在第一个play的末尾添加如下任务:

- name: Sync AD user variables to localhost
  set_fact:
    ad_user_name: "{{ var_name }}"
    ad_user_random_str: "{{ var_random_string }}"
    # 其他需要复用的变量都在这里同步
  delegate_to: localhost
  delegate_facts: true
  run_once: true

第二个play中直接调用即可:

- name: Clone the template and customize
  hosts: localhost
  tasks:
  - name: giveinfo
    debug:
      msg: "{{ hostvars['localhost']['ad_user_name'] }}"

内容的提问来源于stack exchange,提问作者Bryant

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:09:02