Warm tip: This article is reproduced from stackoverflow.com, please click
ansible dictionary

How to remove a single key from an Ansible dictionary?

发布于 2020-03-27 10:26:53

I'd like to remove a single key from a dictionary in Ansible.

For example, I'd like this:

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

To print this:

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

Please note that the dictionary is loaded from a json file and I POST it to the Grafana REST API. I'd like to allow saving an 'id' key in the file and remove the key before POSTing it.

This is closer to the actual use I have for the removal:

- 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"
Questioner
David Resnick
Viewed
291
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

or create a filter plugin and use it.