gpt4 book ai didi

json - Ansible:带冒号的 json 元素带键

转载 作者:行者123 更新时间:2023-12-03 22:53:20 25 4
gpt4 key购买 nike

如何使用 jinja2 rejectattr 删除包含冒号 (:) 的 json 键。

环境:

ansible 2.9.1
config file = None
configured module search path = [u'/home/<user>/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0]

json数据:

   {
"tag:environment": "qa",
"tag:instance_id": "i-123456789"
}

Ansible 剧本:

- name: Remove InstanceID
debug:
msg: "{{ instance_filter | rejectattr('['tag:environment'], 'defined' ') | list }}

实际结果:

fatal: [localhost]: FAILED! => {
"msg": "template error while templating string: expected token ',', got 'tag'. String: {{ instance_filter | rejectattr('['tag:environment'], 'defined' ') | list }}"
}

预期结果:


{
"tag:environment": "qa"
}

最佳答案

rejectattr 确实是用于实现您的目标的关键过滤器之一,但还需要一些其他的东西。这是从您拥有的字典变量中删除特定键的正确过滤器顺序:

剧本:

---
- hosts: localhost
gather_facts: false
vars:
instance_filter:
tag:environment: qa
tag:instance_id: i-123456789

tasks:
- name: print var
debug:
var: instance_filter

- name: manipulate the var
debug:
msg: "{{ instance_filter | dict2items | rejectattr('key', 'equalto', 'tag:instance_id') | list | items2dict }}"

输出:

PLAY [localhost] *******************************************************************************************************************************************************************************************************

TASK [print var] *******************************************************************************************************************************************************************************************************
ok: [localhost] => {
"instance_filter": {
"tag:environment": "qa",
"tag:instance_id": "i-123456789"
}
}

TASK [manipulate the var] **********************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": {
"tag:environment": "qa"
}
}

PLAY RECAP *************************************************************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

希望对您有所帮助。

关于json - Ansible:带冒号的 json 元素带键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com