在一项任务中合并来自不同文件的变量

时间:2020-07-19 10:15:35

标签: variables merge ansible yaml

为了管理一组集群,我想要一个目录vars来存储默认配置,并且出于特定的需要,每个集群都有一个可以添加或覆盖变量的目录。

我正在使用此版本(已简化,并出于说明目的使用调试)

---
- hosts: localhost
  tasks:
    - name: Common has all default variables
      include_vars:
        name: common
        file: "vars/common.yml"

    - name: prod has only dedicated variables and specific to production cluster
      include_vars:
        name: prod
        file: "vars/prod.yml"
    - name: I merge all variables, taking common as base and prod is replacing the existing variable
    - debug:
        msg: "{{ common | combine(prod, recursive=True) }}"

考虑示例

# file vars/common.yml
users:
 - tom
 - sarah

logserver:
  host: default.internal.tld.com
  port: 8443
# file vars/prod.yml
users:
 - tom
 - sarah
 - baptiste

logserver:
  host: prod.internal.tld.com
  index: prd

它给了我

TASK [debug] *****************************************************************************
ok: [localhost] => {
    "msg": {
        "splunk": {
            "host": "prod.internal.tld.com",
            "index": "prod",
            "port": 8443
        },
        "users": [
            "tom",
            "sarah",
            "baptiste"
        ]
    }
}

但是我并不完全满意,因为

  • 它需要一个名称,因此变量不再是顶级
  • 如果我需要添加添加新任务并变长的第三个文件。

我希望有可能在一个插件的帮助下完成一项任务(因为我看到需要合并两个以上的文件),但是我没有找到。

---
- hosts: localhost
  tasks:
    - name: "I'd like to have something like that"
      include_vars:
      # with_combine does not exist but this is to give a idea
      with_combine:
        - vars/common.yml
        - vars/prod.yml

你有什么主意吗?

0 个答案:

没有答案