大网数据广告活动
服务器运维问答

How to merge variables of type hash across different variable files in ansible?

· 52CE 我爱测

I have two YAML variable files which are reused for many playbooks: # playbook/group_vars/all settings: a: 1 b: 2 # inventory/group_vars/main.yml settings: c: 3 I want settings to be equal { a: 1, b: 2, c: 3 } in my playbooks. In…

问题原文

原帖链接 · Jason Holcomb · CC BY-SA 3.0

I have two YAML variable files which are reused for many playbooks:

# playbook/group_vars/all

settings:
  a: 1
  b: 2

# inventory/group_vars/main.yml

settings:
  c: 3

I want settings to be equal { a: 1, b: 2, c: 3 } in my playbooks.

Instead it equals { c: 3 } because inventory/group_vars/* has higher priority than playbook/group_vars/all and because hashes are overridden, not merged.

I see the following options:

  • Define variables separately, using naming conventions and prefixes, instead of using hashes, like so:

    # playbook/group_vars/all
    
    settings_a: 1
    settings_b: 2
    
    # inventory/group_vars/main.yml
    
    settings_c: 3
    

Our team does not consider this solution elegant enough.

  • Use set_fact and/or Jinja's "+" operator

{{ list_common + list_specific }}

This requires changes in many playbooks (we do have many of them) and also looks bad.

--

Are there other options to merge hashes from different files instead of redefining (overriding) them?

What we are trying to achieve is to stop duplicating lists across variable files and define only those parameters which are specific to the group/host.

已采纳解答

原帖链接 · Konstantin Suvorov · CC BY-SA 3.0

First of all, list is [1, 2, 3] and you talk about dictionary {a:1, b:2, c:3} or in other words hash.

There is configurable parameter: hash_behaviour.

By default it is replace, but you can set it to merge to achieve desired behaviour.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-03-07)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。