温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How to remove a single key from an Ansible dictionary?
ansible dictionary

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

发布于 2020-03-27 11:40:24

我想从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"

查看更多

查看更多

提问者
David Resnick
被浏览
110
fumiyas 2017-03-04 00:30
- set_fact:
    dict:
      a: 1
      b: 2
      c: 3
    dict2: {}

- set_fact:
    dict2: "{{dict2 |combine({item.key: item.value})}}"
  when: "{{item.key not in ['a']}}"
  with_dict: "{{dict}}"

- debug: var=dict2

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