我想从 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” key 并在发布之前删除该 key 。
这更接近我删除的实际用途:
- 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
或者创建一个过滤器插件并使用它。
关于dictionary - 如何从 Ansible 字典中删除单个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40496021/