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

Ansible Playbook读取动态Inventory变量失败的问题求助

Ansible Playbook读取动态Inventory变量失败的问题求助

我现在碰到个棘手的问题:想在Playbook里获取Inventory中定义的变量,但执行时总是报错,有没有大佬能帮忙看看怎么正确读取这个变量?

先说明下背景:我的Inventory是动态的,里面的组名在Playbook里是提前不知道的。

我的Inventory文件(ans_hosts)

[gname_tools]
<machine_name_goes_here>
<machine_name_goes_here>
<machine_name_goes_here>

[gname_tools:vars]
group_name=gname_tools
clip_id=3
sub_id=a.b@c.com

我的Playbook文件(var_access.yml)

---
- hosts: all
  connection: local
  gather_facts: false
  tasks:
   - name: Print Inventory variable
     shell: |
       cmd: |
         echo "{{hostvars['group_name']}}"
     register: ExcepStatus
     delegate_to: localhost

   - debug: msg="{{ExcepStatus.stdout}}"

执行Playbook后的报错结果

$ ansible-playbook -i ans_hosts var_access.yml

PLAY [all] **************************************************************************************************************************************************

TASK [Print Inventory variable] *****************************************************************************************************************************
fatal: [<machine_name_goes_here> -> localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: \"hostvars['group_name']\" is undefined\n\nThe error appears to be in '/home/gollip/ans/var_access.yml': line 7, column 6, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n   - name: Print Inventory variable\n     ^ here\n"}

PLAY RECAP **************************************************************************************************************************************************
<machine_name_goes_here>   : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

真心求大家给点解决建议,谢谢啦!

备注:内容来源于stack exchange,提问作者vinWin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 12:03:11