如何从Ansible字典中删除单个键?

时间:2016-11-08 20:40:38

标签: dictionary ansible

我想从Ansible中的字典中删除一个键。

例如,我想这样:

- debug: var=dict2
  vars:
    dict:
      a: 1
      b: 2
      c: 3
    dict2: "{{ dict | filter_to_remove_key('a') }}"

打印出来:

ok: [localhost] => {
    "dict2": {
        "b": 2,
        "c": 3
    }
}

请注意,字典是从json文件加载的,我将其发布到Grafana REST API。我想允许在文件中保存“id”键并在发布之前删除密钥。

这更接近我删除的实际用途:

- name: Install Dashboards   
  uri:
    url: "{{ grafana_api_url }}/dashboards/db"
    method: POST
    headers:
      Authorization: Bearer {{ grafana_api_token }}
    body:
      overwrite: true
      dashboard:
        "{{ lookup('file', item) | from_json | removekey('id') }}"
    body_format: json   with_fileglob:
    - "dashboards/*.json"
    - "../../../dashboards/*.json"

4 个答案:

答案 0 :(得分:7)

{{1}}

或创建一个过滤插件并使用它。

答案 1 :(得分:2)

这是一种受article by John Mazzitelli启发的方法,可以在没有其他set_fact任务等的情况下内联使用:

任务:

tasks:
- debug: var=dict2
  vars:
    dict:
      a: 1
      b: 2
      c: 3
    # It is important that there be NO WHITESPACE outside of `{% ... %}` and `{{ ... }}`
    # or else the var will be converted to a string.  The copy() step optionally prevents
    # modifying the original. If you don't care, then: "{% set removed=dict.pop('a') %}{{dict}}"
    dict2: "{% set copy=dict.copy() %}{% set removed=copy.pop('a') %}{{ copy }}"

输出:

TASK [debug] ***********
ok: [localhost] => {
    "dict2": {
        "b": 2,
        "c": 3
    }
}

答案 2 :(得分:0)

如果您对过滤器感兴趣(我认为这是删除dict中一项的最简洁方法),则在您的剧本所在的目录中创建filter_plugins/dicts.py,并用以下内容填充:

'''Custom ansible filters for dicts'''


class FilterModule(object):

    def filters(self):
        return {
            'del_by_list': self.del_by_list
        }

    def del_by_list(self, dict_to_reduce, list_of_keys):
        ''' Deletes items of dict by list of keys provided'''
        for item in list_of_keys:
            if item in dict_to_reduce:
                del dict_to_reduce[item]
        return dict_to_reduce

您很高兴:

---
- hosts: hadoop
  gather_facts: no
  tasks:

    - debug:
        msg: "{{ {123: 456, 789: 123} | del_by_list([123]) }}"

这将产生{789: 123}

答案 3 :(得分:0)

  - debug: var=dict2
    vars:
      dict:
        a: 1
        b: 2
        c: 3
      dict2: '{{ dict | dict2items | rejectattr("key", "eq", "a") | list | items2dict }}'
      #dict2: '{{ dict | dict2items | rejectattr("key", "match", "^(a|b)$") | list | items2dict }}'

输出:

ok: [localhost] => {
    "dict2": {
        "b": 2,
        "c": 3
    }
}