【问题标题】:Ansible ignoring nested host_varsAnsible 忽略嵌套的 host_vars
【发布时间】:2015-12-13 01:24:54
【问题描述】:

我有以下 Ansible 设置:

playbook.yml

---
- hosts: all
  sudo: true
  vars_files:
    - vars/all.yml
  tasks:
    - debug: msg="foo.bar = {{ foo.bar if foo.bar is defined else False }}"
    - debug: msg="foo_bar = {{ foo_bar if foo_bar is defined else False }}"

vars/all.yml

---
foo:
    greeting: "Hello, world!"

主机/制作

production ansible_ssh_host=xxx.xxx.xxx.xxx ansible_ssh_user=root

host_vars/production

---
foo:
    bar: baz
foo_bar: baz

当我运行 ansible-playbook -i hosts/production playbook.yml 时,我得到以下结果:

TASK: [debug msg="foo.bar = {{ foo.bar if foo.bar is defined else False }}"] *** 
ok: [production] => {
    "msg": "foo.bar = False"
}

TASK: [debug msg="foo_bar = False"] ******************************* 
ok: [production] => {
    "msg": "foo_bar = baz"
}

为什么我的嵌套主机 var foo.bar 不起作用,而顶级主机 var foo_bar 起作用?

【问题讨论】:

    标签: ansible ansible-playbook


    【解决方案1】:

    Ansible 与哈希(字典)一起使用的默认行为不是合并它们,而是用更具体的哈希变量替换优先级较低的哈希变量。所以主机变量胜过组变量,而用vars: 声明的额外变量胜过这两个变量。 Full details here.

    实际上,当您在包含的变量文件中添加“Hello world”时,您正在清除主机变量中的foo 字典。您可以通过添加调试来打印整个哈希来看到这一点:

      tasks:
        - debug: msg="foo.bar = {{ foo.bar if foo.bar is defined else False }}"
        - debug: msg="foo_bar = {{ foo_bar if foo_bar is defined else False }}"
        - debug: var=foo
    

    这增加了这个有用的输出:

    TASK: [debug var=foo] ********************************************************* 
    ok: [vagrantbox] => {
        "var": {
            "foo": {
                "greeting": "Hello, world!"
            }
        }
    }
    
    PLAY RECAP ******************************************************************** 
    vagrantbox                 : ok=4    changed=0    unreachable=0    failed=0   
    

    如果您需要合并foo 中的不同值,您可以使用Jinja combine 过滤器,或者创建本地 ansible.cfg 并将 hash_behaviour 变量设置为合并。

    我发现合并哈希对于使用 Ansible 管理大量服务器是完全必要的,Ansible official docs 建议不要使用它,“除非你认为你绝对需要它”。取决于你的用例,我猜!但它给你的结果正是你的帖子所期望的:

    TASK: [debug msg="foo.bar = {{ foo.bar if foo.bar is defined else False }}"] *** 
    ok: [vagrantbox] => {
        "msg": "foo.bar = baz"
    }
    
    TASK: [debug msg="foo_bar = False"] ******************************************* 
    ok: [vagrantbox] => {
        "msg": "foo_bar = baz"
    }
    
    TASK: [debug var=foo] ********************************************************* 
    ok: [vagrantbox] => {
        "var": {
            "foo": {
                "bar": "baz", 
                "greeting": "Hello, world!"
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多