如何在Ansible中将项目添加到现有字典中?

时间:2019-06-20 14:04:09

标签: list dictionary ansible ansible-inventory

我有一本字典,可通过以下剧本加载:

- name: Get variables from ../main.yml and save them into dict
  include_vars:
    file: "../main.yml"
    name: dict

“ dict”包含以下内容:

"dict": {
"environments": {
    "MYENV": {
        "key1": "value1",
        "key2": "value2"
    },
    "MYENV2": {
        "key1": "value1",
        "key2": "value2"
    },
    "MYENV3": {
        "key1": "value1",
        "key2": "value2"
    }
}}

问题:如何在Ansible中循环浏览此词典,并向“环境”中的每个条目添加带有伴随值的第三个键“ key3”?

所需的情况将是包含以下内容的new_dict:

"new_dict": {
"environments": {
    "MYENV": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    },
    "MYENV2": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    },
    "MYENV3": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    }
}}

“ value3”是类似于“ MYENV” +“ value1” +“ value2”的字符串。

1 个答案:

答案 0 :(得分:1)

需要分解目录。然后添加{key3:value3},目录再次为combined。以下任务

  vars:
    add_this:
      key3: value3
  tasks:
    - set_fact: # collect dictionary keys
        keys: "{{ dict.environments|
                  dict2items|
                  json_query('[].key') }}"
    - set_fact: # collect dictionary values and add item
        values: "{{ dict.environments|
                    dict2items|
                    json_query('[].value')|
                    map('combine', add_this)|list }}"
    - set_fact: # create dict environments
        environments: "{{ environments|
                          default({})|
                          combine({item.0: item.1}) }}"
      loop: "{{ keys|zip(values)|list }}"
    - set_fact: # create dictionary new_dict
        new_dict: "{{ new_dict|
                      default({})|
                      combine({'environments': environments}) }}"
    - debug:
        var: new_dict

给予

"new_dict": {
    "environments": {
        "MYENV": {
            "key1": "value1", 
            "key2": "value2", 
            "key3": "value3"
        }, 
        "MYENV2": {
            "key1": "value1", 
            "key2": "value2", 
            "key3": "value3"
        }, 
        "MYENV3": {
            "key1": "value1", 
            "key2": "value2", 
            "key3": "value3"
        }
    }
}
  

鉴于所有值都是不同的事实,我如何通过以下方式为每个环境动态创建“ value3”:附加“ key1”和“ key2”的值?

带有几个过滤器

$ cat filter_plugins/filter1.py
def custom_1(h):
    return {'key3': h.values()}

def dict_merge(x, y, recursive=False):
    if recursive:
        z = dict(list(x.items()) + list(y.items()))
    else:
        z = x.copy()
        z.update(y)
    return z

def dict_keys(d):
    return list(d)


class FilterModule(object):

    def filters(self):
        return {
            'custom_1' : custom_1,
            'dict_keys' : dict_keys,
            'dict_merge' : dict_merge
        }

以下任务

  tasks:
    - set_fact: 
        env: "{{ env|default({})|
                 combine({item: dict.environments[item]|
                                dict_merge((dict.environments[item]|custom_1), True)
                                }) }}"
      loop: "{{ dict.environments|dict_keys }}"
    - set_fact:
        new_dict: "{{ {}|combine({'environments': env}) }}"
    - debug:
        var: new_dict

给予

"new_dict": {
    "environments": {
        "MYENV": {
            "key1": "value1", 
            "key2": "value2", 
            "key3": [
                "value2", 
                "value1"
            ]
        }, 
        "MYENV2": {
            "key1": "value1", 
            "key2": "value2", 
            "key3": [
                "value2", 
                "value1"
            ]
        }, 
        "MYENV3": {
            "key1": "value1", 
            "key2": "value2", 
            "key3": [
                "value2", 
                "value1"
            ]
        }
    }
}

custom_1 过滤器可满足您的需求。