variables - Ansible:如何在我的剧本中使用 list 文件(主机)中定义的变量?

标签 variables ansible ansible-inventory

正如题主所说。我的主机 list 文件中定义了一些主机变量。如何在我的剧本中访问它们?

这是一个例子。根据我的所有研究,我期望 foobar 成为 hostvars 的一部分。我可以将特定于主机的变量放在单独的 var 文件中,但我希望将它们保存在“附加”到主机的 list 文件中。我不想在模板中使用它。
ansible 版本:1.3.2,ansible_distribution_version:6.4

bash $
bash $ ansible --version
ansible 1.3.2
bash $
bash $ cat test_inv.ini

[foobar]
someHost foo="some string" bar=123
someOtherHost foo="some other string" bar=456


bash $
bash $ cat test.yml

---

- name: test variables...
  hosts: all
  vars:
    - some_junk: "1"
#  gather_facts: no # foo and bar are unavailable whether I gather facts or not.
  tasks:
    - debug: msg="hostvars={{hostvars}}"
    - debug: msg="vars={{vars}}"
    - debug: msg="groups={{groups}}"
    - debug: msg="some_junk={{some_junk}}"
#    - debug: msg="???? HOW DO I PRINT values of host specific variables foo and bar defined in inventory file ???"

bash $
bash $
bash $ ansible-playbook -i test_inv.ini test.yml

PLAY [test variables...] ******************************************************

GATHERING FACTS ***************************************************************
ok: [someHost]

TASK: [debug msg="hostvars={{hostvars}}"] *************************************
ok: [someHost] => {"msg": "hostvars={'someHost': {u'facter_operatingsystem': u'RedHat', u'facter_selinux_current_mode': u'enforcing', u'facter_hostname': u'someHost', 'module_setup': True, u'facter_memoryfree_mb': u'1792.70', u'ansible_distribution_version': u'6.4' // ...........snip...........// u'VMware IDE CDR10'}}"}

TASK: [debug msg="vars={{vars}}"] *********************************************
ok: [someHost] => {"msg": "vars={'some_junk': '1', 'delegate_to': None, 'changed_when': None, 'register': None, 'inventory_dir': '/login/sg219898/PPP/automation/ansible', 'always_run': False, 'ignore_errors': False}"}

TASK: [debug msg="groups={{groups}}"] *****************************************
ok: [someHost] => {"msg": "groups={'ungrouped': [], 'foobar': ['someHost'], 'all': ['someHost']}"}

TASK: [debug msg="some_junk=1"] ***********************************************
ok: [someHost] => {"msg": "some_junk=1"}

PLAY RECAP ********************************************************************
someHost                   : ok=5    changed=0    unreachable=0    failed=0  

bash $ 

最佳答案

执行以下操作应该有效:debug: msg="foo={{foo}}"foo变量将在当前主机的上下文中进行评估。使用 ansible 1.3.4 在本地测试。

关于variables - Ansible:如何在我的剧本中使用 list 文件(主机)中定义的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074736/

相关文章:

java - x=y 是否使 x 指针指向 y?

c - C中的变量名是如何存储在内存中的?

ansible - 将变量传递给 ansible 角色

ansible 动态主机拒绝使用自定义解释器

ansible - 在动态 list 脚本中访问 group_vars/all

javascript - 用于命名变量和函数的单个字母

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

shell - 使用 ansible 打印文件的内容

linux - 使用另一个运行 Ansible 的 Vagrant Linux VM 来配置 Vagrant Linux VM

amazon-ec2 - Ansible aws_ec2 库存插件问题