creating a csv file on localhost with lineinfile

450 views
Skip to first unread message

dulh...@mailbox.org

unread,
Nov 7, 2022, 8:07:31 AM11/7/22
to ansible...@googlegroups.com
I want to create a csv with 3 values per host

the FQDN of the host, a string "postgres" and the stdout of a vairable I have defined

here is my playbook which I am testing againt 3 hosts which all have running postgres, so I expect/aim at 3 lines

###############################################################
---

- hosts: postgres
vars_files: defaults.yml

tasks:
- name: check services - postgresql.service
ansible.builtin.command:
cmd: systemctl is-active postgresql.service
register: pg_active
ignore_errors: true

- name: print value of 'pg_active.stdout'
ansible.builtin.debug:
msg: postgresql is "{{ pg_active.stdout }}"
# when: pg_active.stdout == "active"

- name: check utf8 - postgres (if running)
ansible.builtin.command:
cmd: /opt/db/postgres/postgresql/bin/psql -tAc "SHOW server_encoding;"
when: pg_active.stdout == "active"
register: pg_encoding
become: true
become_user: "{{ postgres_become_user }}"

- name: check utf8 - print value of 'pg_encoding.stdout'
ansible.builtin.debug:
msg: "{{ pg_encoding.stdout }}"
when: pg_active.stdout == "active"

- name: CSV - Create file and set the header
delegate_to: localhost
lineinfile:
dest: "./ignore/{{ ansible_play_name }}.csv"
line:
hostname;dbms;encoding
create: yes
state: present

- name: write result to output.csv
delegate_to: localhost
lineinfile:
dest: "./ignore/{{ ansible_play_name }}.csv"
line: >
{{ ansible_fqdn }};{{ ansible_play_name}};{{ pg_encoding.stdout }}
insertafter: EOF
when: pg_active.stdout == "active"

###################################################################

This basically does what it should. However it creates an empty line between the hosts and does append entries if the output-file already exists.

I am aware that I can delete empty line with lineinfile but was wondering whether there is a way not net create them to begin with.
Reply all
Reply to author
Forward
0 new messages