我有一本字典,它的结构和下面完全一样。
在我挣扎的地方是在Ansible代码中,我将如何让一个用户进入apple,并识别出它的类型是水果?
当用户进入spinach时,Ansible将其识别为素食吗?
基本上,如何在字典中反向检查父级?编辑:在使用selectattr之后,如何将其赋值给将来使用的一个变量?目前,我得到了food_groups \(‘name’,'contains',first).type:水果作为输出,我如何只获得分配给变量的水果?
groups:
- type: fruit
names:
- apple
- oranges
- grapes
- type: veggie
names:
- broccoli
- spinach发布于 2022-01-26 22:17:54
问:“如何让用户输入‘苹果’,并识别出‘水果’的类型?。”
A:创建一个字典,将项目映射到组,例如给定数据
my_groups:
- type: fruit
names:
- apple
- oranges
- grapes
- tomato
- type: veggie
names:
- broccoli
- spinach
- tomato以下任务
- set_fact:
my_dict: "{{ my_dict|d({'undef': 'undef'})|
combine({item.1: [item.0.type]}, list_merge='append') }}"
with_subelements:
- "{{ my_groups }}"
- names给出
my_dict:
apple: [fruit]
broccoli: [veggie]
grapes: [fruit]
oranges: [fruit]
spinach: [veggie]
tomato: [fruit, veggie]
undef: undef我在两组中都添加了“番茄”,以测试多组的成员资格。项目组的标识现在是微不足道的。
- debug:
msg: "{{ my_item|d('undef') }} is {{ my_dict[my_item|d('undef')]|d('none') }}"默认给予
msg: undef is undef当您输入字典中不存在的项时,您将得到
shell> ansible-playbook playbook.yml -e my_item=foo
...
msg: foo is none当您在字典中输入一个项目时,您将得到组(S)。
shell> ansible-playbook playbook.yml -e my_item=spinach
...
msg: spinach is ['veggie']https://stackoverflow.com/questions/70869845
复制相似问题