- hosts: localhost
gather_facts: false
tasks:
- set_fact:
teams: "{{ teams
| default({})
| combine( { item['teamname']: { 'members': [] }
| combine(item) } ) }}"
vars:
raw_string: |
teamname:Cougars
description:Baseball
member:John,second
member:Bill,first
teamname:Rockies
description:Baseball
member:Phil,pitcher
member:Peter,catcher
member:Wilbur,centerfield
teamname:marlins
description:MinorLeague
loop: "{{ raw_string
| regex_replace(':', ': ', multiline=true)
| regex_replace('^member:', ' -', multiline=true)
| split('\n\n')
| map('replace', ' -', 'members:@@@ -', 1)
| map('regex_replace', '@@@', '\n')
| map('from_yaml') }}"
- debug:
var: teams
ok: [localhost] => {
"teams": {
"Cougars": {
"description": "Baseball",
"members": [
"John,second",
"Bill,first"
],
"teamname": "Cougars"
},
"Rockies": {
"description": "Baseball",
"members": [
"Phil,pitcher",
"Peter,catcher",
"Wilbur,centerfield"
],
"teamname": "Rockies"
},
"marlins": {
"description": "MinorLeague",
"members": [],
"teamname": "marlins"
}
}
}
Not the worst thing Iāve ever doneā¦
If thereās an argument you can pass to regex_replace
to limit the number of replacements, that would eliminate the need to resort plain replace
which canāt handle \n
.
Edited to include empty members list and consolidate to one set_fact
.