I’m trying to generate some files using ansible.builtin.template and I would like to use the community.general.to_ini jinja filter.
The problem is that I have an error The error was: ansible.errors.AnsibleFilterError: to_ini failed to parse given dict:'str' object has no attribute 'items'. 'str' object has no attribute 'items'
# some header
{{ config | community.general.to_ini }}
The complete error message is
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ansible.errors.AnsibleFilterError: to_ini failed to parse given dict:'str' object has no attribute 'items'. 'str' object has no attribute 'items'
failed: [debian-12] (item=10-test.sh) => {"action": {"config": {"bl": "environment", "ee": "value"}, "name": "10-test.sh"}, "ansible_loop_var": "action", "changed": false, "msg": "AnsibleFilterError: to_ini failed to parse given dict:'str' object has no attribute 'items'. 'str' object has no attribute 'items'"}
I tried several solutions (like using an intermediate task file and loop over it giving the correct var) but everytime I got this error. It looks like my vars become a string and I can’t loop over it with to_ini.
I don’t understand what is the correct way to do it.
ps: I could probably use community.general.ini_file but I would like to have more control over my file, like add an header as seen in the example.
This means doing it ‘manually’ without using the to_ini filter.
I had thought about it and I may need to do it this way, given my data structure.
But I really want to be able to use (or at least test) the to_ini filter and understand why it doesn’t work in my example. I may want (or need) to use it in another use case.
Could you post your whole backupninja role somewhere so I can run and debug it without having to recreate it — I’m confident I can help you get it working.
Nice
I’ll look at your code in a few days I hope. I’m busy with other things in the mean time.
I’ll comment here if I’m still confused or my code stills has errors.
Thanks
The first problem is indentation. Everything below “mode: '0600'” needs to be shifted two columns to the left.
The second problem is that your simplified daks_backupninja_actions variable has no “section” level(s). The spurious message about the string having no items is because the underlying python module is trying to parse the value of the “bl” section as a dict, but its value is the string “environment”. Throw in another level between “config” and “bl”. (Ironically, your “but at the end something like this” data contains the “section” levels missing from the simplified data.)
Thanks for spotting that, I have written a couple of (probably terrible!) sets of Ansible tasks in the past to detect if “section” level heading are present or not — the from_ini filter doesn’t support files without sections so I’m not surprised that the to_ini filter doesn’t either, it would be nice if they did…