在 yaml 中读取键值对的文本文件 [英] Reading text file in yaml for key-value pairs
问题描述
我有 txtfile(textData.txt) ,其中包含如下键值对:
I have txtfile(textData.txt) which contains key-value pairs like :
user1: john
user2: bob
user3: william
值对的数量是动态的,可以是一个、两个、三个或三个以上,但我的txtFile中至少会有一个值对.
Number of value pairs are dynamic, it can be one, two, three or more than three, but there will be at least one value pair in my txtFile.
我想在我的 yaml 文件中读取这个文本文件,这样我应该得到 yaml 的输出,如:
I want to read this text file in my yaml file in such a way that I should get the output of yaml like :
- name: "User Names"
users:
- userid: user1
username: john
something: false
- userid: user2
username: bob
something: false
- userid: user3
username: william
something: false
我希望这个结构是动态的,这取决于我的 textFile 中有多少值对,但某些内容将保持不变并且不会出现在文件中.请举例说明.
I want this structure to be dynamic, depends on how much value-pairs are there in my textFile but something will remain constant and it won't be present in file. Please help me in it with example.
推荐答案
将文件读入字典并使用 dict2items 创建列表,例如
Read the file into a dictionary and use dict2items to create the list, e.g.
- include_vars:
file: textData.txt
name: users_dict
- set_fact:
users: "{{ users_dict|dict2items(key_name='userid', value_name='username') }}"
给予
users:
- userid: user1
username: john
- userid: user2
username: bob
- userid: user3
username: William
<小时>
,或者把它放到一个文件中,例如
, or put it into a file, e.g.
- copy:
content: |
---
- name: "User Names"
users:
{{ users|to_yaml|indent(width=2) }}
...
dest: users.yml
vars:
users: "{{ users_dict|dict2items(key_name='userid', value_name='username') }}"
给予
shell> cat users.yml
---
- name: "User Names"
users:
- {userid: user1, username: john}
- {userid: user2, username: bob}
- {userid: user3, username: william}
...
shell> yamllint users.yml
<小时>
,或者使用 Jinja 来迭代列表,例如
, or use Jinja to iterate the list, e.g.
- copy:
content: |
---
- name: "User Names"
users:
{% for k,v in users_dict.items() %}
- userid: {{ k }}
username: {{ v }}
{% endfor %}
...
dest: users.yml
给予
shell> cat users.yml
---
- name: "User Names"
users:
- userid: user1
username: john
- userid: user2
username: bob
- userid: user3
username: william
...
shell> yamllint users.yml
这篇关于在 yaml 中读取键值对的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!