dictionary - 如何从 Ansible 字典中删除单个键?

标签 dictionary ansible

我想从 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/

相关文章:

ansible - 仅当子元素存在时才运行任务

Python - 列表中是否可以有字典?

c# - 可以在 C# 4.0 中创建多类型 lambda 函数的单一多类型集合吗?

python - 如何使用 Numba 加速 python 的字典

javascript - 在使用电子邮件作为唯一标识符的同时限制一个人提交表单的次数超过 X 次的最佳方法是什么?

Vagrant 与适用于 Windows 虚拟机的 Ansible

performance - 提高 Ansible 性能

json - 无效操作 : type interface {} does not support indexing

yaml - Ansible AnsibleUndefineVariable 无属性

linux - nohup 和 & 在运行 bash 命令时有什么区别?