在Ansible中,可以使用zip
函数和dict
函数将两个列表转换为键值字典。以下是一个示例代码:
- name: Convert two lists to key-value dictionary
hosts: localhost
gather_facts: false
vars:
keys: ['name', 'age', 'gender']
values: ['John', '25', 'Male']
tasks:
- name: Create key-value dictionary
set_fact:
my_dict: "{{ dict(keys|zip(values)) }}"
- name: Print the dictionary
debug:
var: my_dict
在上面的示例中,我们定义了两个列表keys
和values
,分别包含键和对应的值。然后使用zip
函数将两个列表进行组合,再使用dict
函数将组合后的列表转换为字典。最后,使用set_fact
模块将字典保存到变量my_dict
中。
你可以通过debug
模块来查看转换后的字典结果。运行以上代码,输出结果应该类似于:
TASK [Print the dictionary] *********************************************************
ok: [localhost] => {
"my_dict": {
"age": "25",
"gender": "Male",
"name": "John"
}
}
这样,两个列表就成功转换为了键值字典。