Ansible 在 csv 文件的新行上打印 ps

问题描述 投票:0回答:1

这里是ansible新手用户。

我正在尝试将 ps 的输出打印到 csv 文件中,但不知何故它打印在下一列而不是下一行。

这是我的剧本 xml:

- name: Write running process into a csv file
  hosts: servers
  gather_facts: yes

  vars:
    output_path: "./reports/"
    filename: "process_{{ date }}.csv"

  tasks:
  - name: CSV - Generate output filename
    set_fact: date="{{lookup('pipe','date +%Y%m%d%H%M%S')}}"
    run_once: true

  - name: CSV - Create file and set the header
    lineinfile:
      dest: "{{ output_path }}/{{ filename }}"
      line:
        PID,Started,CPU,Memory,User,Process
      create: yes
      state: present
    delegate_to: localhost

  - name: CSV - Get ps cpu
    ansible.builtin.shell:
      ps -e -o %p, -o lstart -o ,%C, -o %mem -o user, -o %c --no-header
    register: ps

  - name: CSV - Write into csv file
    lineinfile:
      insertafter: EOF
      dest: "{{ output_path }}/{{ filename }}"
      line: "{inventory_hostname}},{{ps.stdout_lines}}"
    loop: "{{ ps.stdout_lines }}"
    delegate_to: localhost

  - name: CSV - Blank lines removal
    lineinfile:
      path: "./{{ output_path }}/{{ filename }}"
      state: absent
      regex: '^\s*$'
    delegate_to: localhost


电流输出就像

enter image description here

所需输出示例:

enter image description here


linux csv ansible process
1个回答
1
投票

...但不知何故它打印在下一列而不是下一行...当前输出就像...

这是因为在您的任务“CSV - 写入 CSV 文件”中,您正在打印每个迭代步骤的所有

stdout_lines
,而不是仅打印迭代步骤的行。

要逐行打印,可以使用类似的方法

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: CSV - Get ps cpu
    shell:
      cmd: ps -e -o %p, -o lstart -o ,%C, -o %mem -o user, -o %c --no-header
    register: ps

  - name: Show 'stdout_lines' one line per iteration for CSV
    debug:
      msg: "{{ inventory_hostname }}, {{ ps.stdout_lines[item | int] }}"
    loop: "{{ range(0, ps.stdout_lines | length) | list }}"
© www.soinside.com 2019 - 2024. All rights reserved.