How to convert a string with key value pairs into a list of dictionaries?

爱⌒轻易说出口 提交于 2020-01-23 18:16:07

问题


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}

in tower survey, I can put similar info as textarea in survey:

dbid: 1, dbname: abc
dbid: 2, dbname: xyz

How can I convert my textarea data into a list of dictionary? I can't find any suitable jinj2 filter for conversion.

my ansible version is 2.4.


回答1:


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 }}

Where that select in the pipeline is designed to strip off any empty lines (since those lines will not be True-thy)



来源:https://stackoverflow.com/questions/54814628/how-to-convert-a-string-with-key-value-pairs-into-a-list-of-dictionaries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!