Smily
Smily

Reputation: 2578

Write to csv file

I need some contents to be written in csv format to a file using ansible

shell: ps -ef | grep java | awk '{print $1}'
register: username

shell: ps -ef | grep java | awk '{print $2}'
register: id

The output for username will be similar to :

root
admin
test_admin

The output for id will be similar to:

1232
4343
2233

so I want this to be written to a csv file as

root,1232
admin,4343
test_admin,2233

Please suggest.

Upvotes: 4

Views: 12949

Answers (1)

Alassane Ndiaye
Alassane Ndiaye

Reputation: 4787

You can use a combination of the zip, map and join filters to achieve your desired result:

- hosts: all
  tasks:
    - name: combination of two lists
      set_fact:
        lines: "{{ [1,2,3]|zip(['a','b','c'])|list }}"
    - debug:
        msg: "{{ lines }}"
    - name: transform each line into a string
      set_fact:
        lines: "{{ lines | map('join', ', ') | list }}"
    - debug:
        msg: "{{ lines }}"
    - name: combine lines
      set_fact:
        lines: "{{ lines | join('\n') }}"
    - debug:
        msg: "{{ lines }}"
    - name: write lines to file
      copy:
        content: "{{ lines }}"
        dest: "output.csv"

Or when you combine the filters together:

- name: write lines to file
  copy:
    content: "{{ [1,2,3] | zip(['a','b','c']) | map('join', ', ')  | join('\n') }}"
    dest: "output.csv"

The content of output.csv will be:

1, a
2, b
3, c

Upvotes: 5

Related Questions