Ansible 主机变量未定义

Ansible hostvars undefined

我有一个非常简单的游戏,可以保存变量并在主机变量中查找它们。

- name: Set hostvars
  hosts: localhost
  vars:
    var_one: "I am a"
    var_two: "test"
  tasks:
    - debug: var=hostvars['localhost']['var_one']
    - debug: var=hostvars['localhost']['var_two']

然而,当我运行玩这个游戏时,变量没有定义:

PLAY [Set hostvars] ************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "hostvars['localhost']['var_one']": "VARIABLE IS NOT DEFINED!"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "hostvars['localhost']['var_two']": "VARIABLE IS NOT DEFINED!"
}

如何将这些变量保存在 hostvars 中?

您可以使用 set_fact 模块设置主机事实 运行时间:

---
- name: Set hostvars
  hosts: localhost
  tasks:
    - set_fact: var_one="I am a"
    - set_fact: var_two="test"
    - debug: var=hostvars['localhost']['var_one']
    - debug: var=hostvars['localhost']['var_two']

引用 the documentation:

这些变量将在 Ansible 运行 期间的播放之间存在,但即使您使用事实缓存也不会在执行过程中保存。

尝试使用

msg=

而不是 var=。根据调试模块的帮助

var - A variable name to debug. Mutually exclusive with the 'msg' option.

- name: Set hostvars
  hosts: localhost
  vars:
    var_one: I am a
    var_two: est
  tasks:
    - debug: msg=hostvars['localhost']['var_one']
    - debug: msg=hostvars['localhost']['var_two']
...



PLAY [Set hostvars] ************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "hostvars['localhost']['var_one']"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "hostvars['localhost']['var_two']"
}

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0

这里可以看出事实(绑定到 Ansible 目标主机的变量)和常规变量之间的区别。

变量在内部存储在 vars 结构中,因此您可以通过以下方式访问它们:

tasks:
  - debug: var=vars['var_one']
  - debug: var=vars['var_two']

另一方面,事实存储在 hostvars


在任何一种情况下,除非您引用的是具有动态名称的变量名,或者绑定到另一台主机而不是执行任务的事实,否则您可以简单地使用 variable/fact 名称,方法是使用其姓名:

tasks:
  - debug: var=var_one
  - debug: var=var_two