Ansible写入ps输出到CSV时列错位,如何实现逐行写入?
解决Ansible将ps输出写入CSV时列错位的问题
问题根源
你的Playbook存在两个核心问题导致CSV列错位:
- 写入逻辑错误:循环写入时误用了整个
ps.stdout_lines列表而非当前循环项item,还存在语法错误({inventory_hostname}}多了一个闭合大括号) - ps输出格式不兼容CSV:原ps命令的输出没有处理含空格的字段(比如进程启动时间),且分隔符不规范,导致CSV解析时把空格当成列分隔符。
修正后的Playbook
- name: Write running process into a csv file hosts: servers gather_facts: yes vars: output_path: "./reports/" filename: "process_{{ ansible_date_time.strftime('%Y%m%d%H%M%S') }}.csv" tasks: - name: CSV - Ensure output directory exists file: path: "{{ output_path }}" state: directory delegate_to: localhost run_once: true - name: CSV - Create file and set the header lineinfile: dest: "{{ output_path }}/{{ filename }}" line: "Hostname,PID,Started,CPU,Memory,User,Process" create: yes state: present delegate_to: localhost run_once: true - name: CSV - Get ps output formatted for CSV ansible.builtin.shell: | ps -e -o "%p," -o "lstart," -o "%C," -o "%mem," -o "%U," -o "%c" --no-header | sed 's/^\(.* [0-9]\{4\}\)/"&"/' register: ps_output - name: CSV - Write process data to CSV lineinfile: insertafter: EOF dest: "{{ output_path }}/{{ filename }}" line: "{{ inventory_hostname }},{{ item }}" loop: "{{ ps_output.stdout_lines }}" delegate_to: localhost - name: CSV - Remove blank lines lineinfile: path: "{{ output_path }}/{{ filename }}" state: absent regex: '^\s*$' delegate_to: localhost run_once: true
关键修正说明
- 替换日期生成方式:用
ansible_date_time变量替代lookup('pipe','date'),避免跨节点时间不一致问题 - 规范ps输出:
- 用
"%p,"这类带逗号的格式指定每个字段的输出,确保分隔符统一 - 用
sed把启动时间(带空格的字段)用双引号包裹,避免CSV解析时拆分列
- 用
- 修复写入逻辑:循环时使用
item获取当前进程的输出行,修正inventory_hostname的语法错误 - 新增目录检查:确保输出目录存在,避免文件创建失败
内容的提问来源于stack exchange,提问作者Pro
相关产品推荐
相关产品推荐

