如何从 Ansible 字典中删除单个键? [英] How to remove a single key from an Ansible dictionary?
本文介绍了如何从 Ansible 字典中删除单个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从 Ansible 的字典中删除一个键.
I'd like to remove a single key from a dictionary in 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"键并在发布之前删除它.
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"
推荐答案
- 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.
这篇关于如何从 Ansible 字典中删除单个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文