请求协助:将Ansible采集的HMC文件系统数据转为字典并上传至Splunk
解决Ansible在HMC环境中生成文件系统字典并上传Splunk HEC的问题
问题核心原因
循环使用set_fact时未配置合并规则,会导致变量被反复覆盖,无法生成包含所有文件系统的统一字典/事件;另外HMC受限Bash的输出格式需要额外处理才能结构化。
分步解决方法
1. 结构化采集文件系统数据
通过shell模块采集标准化格式的文件系统数据,规避原始df输出的换行、空格问题:
- name: 采集HMC文件系统数据 shell: df -P | awk 'NR>1 {printf "{\"filesystem\":\"%s\",\"size\":\"%s\",\"used\":\"%s\",\"avail\":\"%s\",\"use_pct\":\"%s\",\"mount_point\":\"%s\"}\n", $1,$2,$3,$4,$5,$6}' register: fs_raw_output args: warn: false
用awk直接输出单行JSON格式数据,后续可直接解析为结构化对象。
2. 生成统一事件字典
将采集到的单行JSON数据合并为包含所有文件系统的事件字典:
- name: 构建文件系统事件字典 set_fact: fs_event: >- { "host": "{{ inventory_hostname }}", "source": "hmc_filesystem", "sourcetype": "linux:df", "event": { "filesystems": {{ fs_raw_output.stdout_lines | map('from_json') | list }} } }
stdout_lines将每行JSON转为列表元素map('from_json')把字符串转为JSON对象list将结果转为列表,嵌入到事件的filesystems字段中
3. 上传至Splunk HEC
按照Splunk HEC要求配置uri模块发送POST请求:
- name: 上传事件至Splunk HEC uri: url: "https://your-splunk-hec-endpoint:8088/services/collector" method: POST headers: Authorization: "Splunk your-hec-token" body: "{{ fs_event | to_json }}" body_format: json validate_certs: no # 根据实际环境调整 status_code: 200
完整Playbook示例
--- - name: HMC文件系统数据采集并上传Splunk hosts: hmc_servers gather_facts: no tasks: - name: 采集HMC文件系统数据 shell: df -P | awk 'NR>1 {printf "{\"filesystem\":\"%s\",\"size\":\"%s\",\"used\":\"%s\",\"avail\":\"%s\",\"use_pct\":\"%s\",\"mount_point\":\"%s\"}\n", $1,$2,$3,$4,$5,$6}' register: fs_raw_output args: warn: false - name: 构建文件系统事件字典 set_fact: fs_event: >- { "host": "{{ inventory_hostname }}", "source": "hmc_filesystem", "sourcetype": "linux:df", "event": { "filesystems": {{ fs_raw_output.stdout_lines | map('from_json') | list }} } } - name: 调试输出事件字典 debug: var: fs_event - name: 上传事件至Splunk HEC uri: url: "https://your-splunk-hec-endpoint:8088/services/collector" method: POST headers: Authorization: "Splunk your-hec-token" body: "{{ fs_event | to_json }}" body_format: json validate_certs: no status_code: 200
关键注意事项
- 若HMC受限Bash不支持高级
awk特性,可改用cut分割后拼接JSON:df -P | tail -n +2 | while read line; do echo "{\"filesystem\":\"$(echo $line | cut -d' ' -f1)\",\"size\":\"$(echo $line | cut -d' ' -f2)\",\"used\":\"$(echo $line | cut -d' ' -f3)\",\"avail\":\"$(echo $line | cut -d' ' -f4)\",\"use_pct\":\"$(echo $line | cut -d' ' -f5)\",\"mount_point\":\"$(echo $line | cut -d' ' -f6-)\"}"; done - 如需单文件系统单事件上传,可循环处理每行数据:
- name: 逐个上传文件系统事件 uri: url: "https://your-splunk-hec-endpoint:8088/services/collector" method: POST headers: Authorization: "Splunk your-hec-token" body: >- { "host": "{{ inventory_hostname }}", "source": "hmc_filesystem", "sourcetype": "linux:df", "event": {{ item | from_json }} } body_format: json validate_certs: no status_code: 200 loop: "{{ fs_raw_output.stdout_lines }}"
内容的提问来源于stack exchange,提问作者satsensort
相关产品推荐
相关产品推荐

