我有以下词典:
question:
first_run:
app:
- answer: null
name: first_name
question: What is your First name?
- answer: null
name: last_name
question: What is your Last name?
core:
- question: question1
- question: question2
answer:
first_name: John
last_name: Smith
我使用以下任务手动更新question.first_run.app下的答案值,效果很好
- name: Update question variable
set_fact:
question:
first_run:
app:
- name: first_name
question: "What is your First name?"
answer: "{{ answer.first_name }}"
- name: last_name
question: "What is your Last name?"
answer: "{{ answer.last_name }}"
我还测试了以下任务(对于这种情况,这将是更可取的方法)
- name: "TEST-1"
set_fact:
question: "{{ question | combine({'first_run': {'app': question.first_run.app | map('combine', {'answer': update }) | list }}, recursive=True) }}"
loop: "{{ question.first_run.app }}"
vars:
update: "{{ answer[item.name] if item.name in answer.keys() else item.answer }}"
- name: "TEST-2"
set_fact:
question: "{{ question | combine({'first_run': {'app': question.first_run.app | map('combine', {'answer': (answer[item.name])})}}, recursive=True) }}"
loop: "{{ question.first_run.app }}"
vars:c
update: "{{ answer | dict2items | selectattr('key', 'in', [item.name]) | map(attribute='value') | first }}"
# update: "{{ answer[item.name] }}" # THis also works
但是 TEST-1 和 TEST-2 的输出总是这样的:
question:
first_run:
app:
- answer: Smith
name: first_name
question: What is your First name?
- answer: Smith
name: last_name
question: What is your Last name?
core:
- question: question1
- question: question2
我测试的最后一个任务是:
它可以工作,但所需的结果保存在新的 var app_list 下
- name: "TEST-3"
set_fact:
question: "{{ question | combine({'first_run': {'app': app_list}}, recursive=True) }}"
vars:
app_list: []
loop: "{{ question.first_run.app }}"
set_fact:
app_list: "{{ app_list + [item | combine({'answer': answer[item.name]})] }}"
问题:
我需要更新任务“更新问题变量”,这样我就不必手动放置数组question.first_run.app中的所有这些键
我如何使用循环将question.first_run.app.name与answer.key匹配,以便输出看起来像这样?最好调整 TEST-1 或 TEST-2 或 TEST-3
question:
first_run:
app:
- answer: John
name: first_name
question: What is your First name?
- answer: Smith
name: last_name
question: What is your Last name?
core:
- question: question1
- question: question2