You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible写入ps输出到CSV时列错位,如何实现逐行写入?

解决Ansible将ps输出写入CSV时列错位的问题

问题根源

你的Playbook存在两个核心问题导致CSV列错位:

  1. 写入逻辑错误:循环写入时误用了整个ps.stdout_lines列表而非当前循环项item,还存在语法错误({inventory_hostname}}多了一个闭合大括号)
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:05:23