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"
- 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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With