Convert from many text lines to a list of dictionaries items.
I'm trying to convert a configuration file to a list of dict entries. That list can by used by Ansible for various tasks. The file is a general text .conf file with "item=value" pairs. I need to convert the file to a list of dicts. variable => [ "item1":"value", "item2":"value", ... ]
I followed this solution: Converting output of Python script to dict in Ansible Got a partial solution as I only got the last line from the file and only one dict in the variable. (A single dict list)
A part of the .conf file
# Flags if dhcp should be used or not
use_dhcp=1
# The NOS300s IP address
ip_address=
# Netmask to use for this NOS300
netmask=
# Default gateway
gateway=
# DNS Server
dns_server=
# Local folder to download the files to (required, absolute path)
# download_folder = /tmp
All of the comments and blanks need to be removed and then convert the lines with '=' into a list of dicts.
<< playbook def >>
vars:
remote_config_file: /etc/my/general.conf
tasks:
- name: "Get {{ remote_config_file }} to a list of terms and add to var"
shell: "egrep -v \'(^$|^#)\' {{remote_config_file}} | grep \'=\' "
register: NosConf
- name: "Convert to dict list"
set_fact:
NosFactDict: "{{ parameter | default({}) | combine ( { item.split('=')[0]: item.split('=')[1] } ) }}"
with_items: "{{ NosConf.stdout_lines }}"
- debug:
msg: "{{ NosFactDict }}"
The shell command strips the blank and commented lines then filters the lines with '=' then split and combine the filtered line to a dict.
I want a list longer then:
task path: /media/sf_Virtualbox-share/FactfileAdd.yml:30
ok: [192.168.2.112] => {
"msg": {
"docker0_network": "172.17.0.0/16"
}
}
It need to be more then
ok: [192.168.2.112] => {
"msg": {
"base_path": "/var/www/desert",
"buildnumber": "os",
...
"use_proxy": "0",
"use_sat_distribution": "0",
"version": "1.6.1.8-os"
}
}