拆分行,split和trim项,并使用过滤器community.general.dict创建字典
info_dict1: "{{ info.splitlines()|
map('split', ',')|
map('map', 'trim')|
map('zip', ['dev', 'spec', 'dsync', 'dir', 'disk', 'size', 'free'])|
map('map', 'reverse')|
map('community.general.dict') }}"
给
info_dict1:
- dev: XYZ_data_001 file system device
dir: directio on
disk: physical disk
dsync: dsync off
free: 'Free: 0.00 MB 2 0 6 0 8388607'
size: 16384.00 MB
spec: special
- dev: XYZ_data_002 file system device
dir: directio on
disk: physical disk
dsync: dsync off
free: 'Free: 0.00 MB 2 0 13 0 8388607'
size: 16384.00 MB
spec: special
- 拆分属性开发并使用过滤器community.general.dict_kv创建具有属性的字典列表设备
info_dev: "{{ info_dict1|map(attribute='dev')|
map('split')|
map('first')|
map('community.general.dict_kv', 'device') }}"
给
info_dev:
- device: XYZ_data_001
- device: XYZ_data_002
合并字典
info_dict2: "{{ info_dict1|zip(info_dev)|map('combine') }}"
给
info_dict2:
- dev: XYZ_data_001 file system device
device: XYZ_data_001
dir: directio on
disk: physical disk
dsync: dsync off
free: 'Free: 0.00 MB 2 0 6 0 8388607'
size: 16384.00 MB
spec: special
- dev: XYZ_data_002 file system device
device: XYZ_data_002
dir: directio on
disk: physical disk
dsync: dsync off
free: 'Free: 0.00 MB 2 0 13 0 8388607'
size: 16384.00 MB
spec: special
这样您就可以根据需要添加其他属性。
问:“搜索特定单词 XYZ_data_001 并获取大小。”
A:创建字典设备大小
device_size: "{{ info_dict2|items2dict(key_name='device', value_name='size') }}"
给
device_size:
XYZ_data_001: 16384.00 MB
XYZ_data_002: 16384.00 MB
查字典
- debug:
msg: "Size of XYZ_data_001 is {{ device_size.XYZ_data_001 }}"
给
msg: Size of XYZ_data_001 is 16384.00 MB
用于测试的完整剧本示例
- hosts: localhost
vars:
info: |
XYZ_data_001 file system device, special, dsync off, directio on, physical disk, 16384.00 MB, Free: 0.00 MB 2 0 6 0 8388607
XYZ_data_002 file system device, special, dsync off, directio on, physical disk, 16384.00 MB, Free: 0.00 MB 2 0 13 0 8388607
info_dict1: "{{ info.splitlines()|
map('split', ',')|
map('map', 'trim')|
map('zip', ['dev', 'spec', 'dsync', 'dir', 'disk', 'size', 'free'])|
map('map', 'reverse')|
map('community.general.dict') }}"
info_dev: "{{ info_dict1|map(attribute='dev')|
map('split')|
map('first')|
map('community.general.dict_kv', 'device') }}"
info_dict2: "{{ info_dict1|zip(info_dev)|map('combine') }}"
device_size: "{{ info_dict2|items2dict(key_name='device', value_name='size') }}"
tasks:
- debug:
var: info_dict1
- debug:
var: info_dev
- debug:
var: info_dict2
- debug:
var: device_size
- debug:
msg: "Size of XYZ_data_001 is {{ device_size.XYZ_data_001 }}"