Create a file with static line and addtional lines based on configuration

Hi,

I’m trying to run the following tasks using LineInFile, but I’m facing few issues

Tasks :

    1. In case the file exists it should be deleted and recreated
    1. First-line should be static
    1. Next lines based on configuration
    1. Need to upload to HDFS – Done

Configuration file

cars:

  • brand: mazda
    color: red

  • brand: opel
    color: black

Playbook

- hosts: bigdata_worker[0]

  become: true

  vars_files:

    - ./hdfs-folder-and-permission-config.yml

  tasks:

  - name: Create cars.csv file

    lineinfile:

      path: /tmp/cars.csv

      line: 
         - brand,color
         - "{{ item.brand }},{{ item.color }}"

      create: yes

    with_items: "{{ cars }}"

  - name: upload file to HDFS

    shell: hdfs dfs -put /tmp/cars.csv /{{ root_dir_name }}

Problems:

    1. The file is modified instead of recreated

[‘brand,color’, ‘mazda,red’]

[‘brand,color’, ‘opel,black’]

[‘brand,color’, ‘subaru,black’] ; This is when I have updated one of the brands on the second run

    1. File output is not as a wanted – This is what I need

Brand,color

Mazda,red

Opel,blak

Hi,

this could be done with a jinja-template:

`
tasks:

  • name: Create cars.csv file
    copy:
    dest: /tmp/cars.csv
    content: |
    Brand,colour
    {% for item in cars%}
    {{item.brand}},{{item.color}}
    {% endfor %}

`

(I used the inline version with copy, another way is to use template-module with external template-file.)

Best regards,

Sven