首页 > 解决方案 > 需要在 Ansible 中使用主机变量(ansible engine 2.8 & ansible tower 3.5)

问题描述

需要您的帮助来实现以下目标: - 在 Ansible 清单中使用与 hostIP 内联的变量(即主机变量)

我的库存:

[ora_patch]
10.24.29.14 SID=orcl,orcl2

我的剧本:

---
- hosts: [ora_patch]
  tasks:
  - debug:
     var: "{{ hostvars[ansible_host]['SID'] }}"

输出**我得到**:

PLAY [ora_patch] ************************************************************

TASK [patch_ora_si_122 : debug] *****************************************
ok: [10.24.29.14] => {
    "orcl,orcl2": "(Undefined, Undefined)"
}

PLAY RECAP ******************************************************************
10.24.29.14               : ok=1    changed=0    unreachable=0    failed=0

输出**我想要**:

PLAY [ora_patch] ***********************************************************

TASK [patch_ora_si_122 : debug] ****************************************
ok: [10.24.29.14] => {
    "SID": "orcl,orcl2"
}

PLAY RECAP *****************************************************************
10.24.29.14               : ok=1    changed=0    unreachable=0    failed=0

我执行的命令:

ansible-playbook -i inventory patch_ora_si_122.yml

标签: ansibleansible-inventory

解决方案


你的剧本有点错误。您正在尝试使用 hostvar 的内容"{{ hostvars[ansible_host]['SID'] }}"作为变量名来显示debug: var=....

只需将您的剧本更改为

---
- hosts: ora_patch
  tasks:
  - debug:
     msg: "SID: {{ hostvars[ansible_host]['SID'] }}"

或者你也可以直接使用变量名:

---
- hosts: ora_patch
  tasks:
  - debug:
     var: SID

推荐阅读