You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ansible include_vars合并变量失败:报NoneType与AnsibleMapping错误

问题解决:Ansible合并变量文件时出现NoneType错误

错误原因

include_vars模块并不支持hash_behaviour参数,你在模块配置中添加的这个参数是无效的,会导致变量加载与合并逻辑异常,最终触发"NoneType与AnsibleMapping无法合并"的错误。hash_behaviour属于Ansible全局配置项,需通过play变量或ansible.cfg文件设置,而非直接作为模块参数使用。

解决方案

方案1:通过Play变量设置合并行为

在Play级别配置ansible_hash_behaviour: merge,让Ansible默认采用合并模式处理字典变量:

- name: 合并vars目录下的变量文件
  hosts: localhost
  vars:
    ansible_hash_behaviour: merge
  tasks:
    - name: 加载vars目录下所有变量文件
      ansible.builtin.include_vars:
        dir: "vars"
    - name: 输出合并后的test_var
      ansible.builtin.debug:
        var: test_var

方案2:手动使用combine过滤器合并

如果不想修改全局合并行为,可手动加载变量并通过combine过滤器递归合并字典:

- name: 手动合并vars目录下的变量文件
  hosts: localhost
  tasks:
    - name: 将vars目录下的变量加载为列表
      ansible.builtin.include_vars:
        dir: "vars"
        name: loaded_vars
        flatten: false
    - name: 递归合并test_var字典
      ansible.builtin.set_fact:
        test_var: "{{ test_var | default({}) | combine(item.test_var, recursive=True) }}"
      loop: "{{ loaded_vars }}"
    - name: 输出合并后的test_var
      ansible.builtin.debug:
        var: test_var

执行上述任一方案后,都能得到你期望的合并结果:

test_var:
  test1: foo
  test2: bar

内容的提问来源于stack exchange,提问作者Subbeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:32:52