【发布时间】:2019-08-20 09:17:44
【问题描述】:
从多行文本转换为字典项目列表。
我正在尝试将配置文件转换为 dict 条目列表。 Ansible 可以将该列表用于各种任务。该文件是具有“item=value”对的通用文本 .conf 文件。我需要将文件转换为字典列表。变量 => [ "item1":"value", "item2":"value", ... ]
我遵循了这个解决方案:Converting output of Python script to dict in Ansible 得到了部分解决方案,因为我只得到了文件的最后一行,变量中只有一个 dict。 (单个字典列表)
.conf 文件的一部分
# 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
需要删除所有的 cmets 和空白,然后将带有 '=' 的行转换为字典列表。
<< 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 }}"
shell 命令去除空白行和注释行,然后使用 '=' 过滤这些行,然后将过滤后的行拆分并合并为一个字典。
然后我想要一个更长的列表:
task path: /media/sf_Virtualbox-share/FactfileAdd.yml:30
ok: [192.168.2.112] => {
"msg": {
"docker0_network": "172.17.0.0/16"
}
}
应该是更多
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"
}
}
【问题讨论】:
-
如果有multiline values,
NosConf不会保留所有数据。
标签: string dictionary ansible jinja2