如何在Ansible变量文件中直接合并字典
问题:如何在Ansible变量文件中合并字典,直接使用
servers.server1变量? 我希望在任务中直接调用servers.server1变量,不需要额外的set_fact步骤。请问怎么在任务外的变量文件里完成变量替换,把多个字典合并到servers.server1中?
当前变量文件var/main.yaml内容:
common_parts_1: storage: type: nfs value: 10GB common_parts_2: cpu: cores: 2 memory: value: 2GB servers: server1: name: superPC owner: John "{{ common_parts_1 }}" "{{ common_parts_2 }}"
预期合并后的结果:
servers: server1: name: superPC owner: John storage: type: nfs value: 10GB cpu: cores: 2 memory: value: 2GB
解决方法
直接在YAML字典里插入模板字符串的写法不符合语法要求,也无法自动合并字典。需要用Ansible的combine过滤器实现多字典合并,修改变量文件如下:
方式一:直接合并基础字段与公共部分
# var/main.yaml common_parts_1: storage: type: nfs value: 10GB common_parts_2: cpu: cores: 2 memory: value: 2GB servers: server1: "{{ {'name': 'superPC', 'owner': 'John'} | combine(common_parts_1) | combine(common_parts_2) }}"
方式二:拆分基础字段为单独变量(更易维护)
如果server1的基础字段较多,可以先定义单独的基础字典变量,再合并公共部分:
# var/main.yaml common_parts_1: storage: type: nfs value: 10GB common_parts_2: cpu: cores: 2 memory: value: 2GB server1_base: name: superPC owner: John servers: server1: "{{ server1_base | combine(common_parts_1) | combine(common_parts_2) }}"
说明
combine过滤器会将多个字典的键值对合并为一个新字典,若存在重复键,后面的字典会覆盖前面的内容。- 按上述方式定义后,在任务中可直接使用
servers.server1,无需额外处理就能获取合并后的完整字典。
内容的提问来源于stack exchange,提问作者Kucharsky
相关产品推荐
相关产品推荐

