从 playbook 中的 Ansilbe 主机文件打印变量

问题描述 投票:0回答:1

尝试在剧本中获取变量值,但会产生如下错误。有什么解决变量的建议吗?

这是(例如动态)清单文件(其中组名称在剧本中未知)

$ cat 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
[email protected]

这是剧本

$ cat 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}}"

这是运行剧本的结果

$ 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
ansible ansible-inventory
1个回答
0
投票

hostvars 是主机的字典,其中每个键都是主机变量的字典。要从

hostvars
获取变量,您应该首先指定要访问其变量的主机:

- debug:
    var: hostvars['<machine_name_goes_here>']['group_name']
© www.soinside.com 2019 - 2024. All rights reserved.