Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a single key from an Ansible dictionary?

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"
like image 309
David Resnick Avatar asked Nov 08 '16 20:11

David Resnick


1 Answers

  - 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 }}'

Output:

ok: [localhost] => {
    "dict2": {
        "b": 2,
        "c": 3
    }
}
like image 182
Sergei Avatar answered Sep 24 '22 14:09

Sergei