问题
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