Pro
Pro

Reputation: 91

Ansible to print ps on new row of csv file

Newbie ansible user here.

I'm trying to print output of ps into csv file but somehow its printing on next column rather than next row.

This is my playbook 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


current output is like

enter image description here

Example of desired output :

enter image description here


Upvotes: 0

Views: 383

Answers (1)

U880D
U880D

Reputation: 12145

... but somehow its printing on next column rather than next row ... current output is like ...

This is because within your task "CSV - Write into CSV file" you are printing out all stdout_lines for each iteration steps instead of one, the line for the iteration step only.

To print out line by line one could use an approach like

---
- 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 }}"

Upvotes: 1

Related Questions