如何将具有键值对的字符串转换为词典列表? [英] How to convert a string with key value pairs into a list of dictionaries?
问题描述
我正在尝试将我的剧本迁移到ansible塔式环境中.在我的剧本中,我定义了db_list之类的变量:
I am trying to migrate my playbooks into ansible tower environment. In my playbook, I defined variables like db_list:
db_list:
- { dbid: 1, dbname: abc}
- { dbid: 2, dbname: xyz}
在塔式调查中,我可以在调查中输入与textarea类似的信息:
in tower survey, I can put similar info as textarea in survey:
dbid: 1, dbname: abc
dbid: 2, dbname: xyz
如何将我的textarea数据转换为字典列表?我找不到任何合适的jinj2过滤器进行转换.
How can I convert my textarea data into a list of dictionary? I can't find any suitable jinj2 filter for conversion.
我的ansible版本是2.4.
my ansible version is 2.4.
推荐答案
假设textarea的内容位于名为textarea
的变量中,则可以利用yaml非常自由的事实:
Assuming the contents of the textarea are in a variable called textarea
, you can take advantage of the fact that yaml is pretty liberal:
- set_fact:
db_list: >-
{{ textarea.split("\n") | select |
map("regex_replace", "^", "- {") |
map("regex_replace", "$", "}") |
join("\n") | from_yaml }}
管道中的select
旨在删除任何空行(因为这些行将不是True-thy)
Where that select
in the pipeline is designed to strip off any empty lines (since those lines will not be True-thy)
这篇关于如何将具有键值对的字符串转换为词典列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!