As @mdaniel mentioned, there's no out-of-box write_csv
module in Ansible. Without creating your own module, the only workaround I can think of is the following:
- You read in the CSV file with
read_csv
module and register the data table as a dictionary variable.
- You add the new values to the dict variable recursively with the key "mark". (Check this post for modifying values in dict variable)
- You loop over the dict variable and output each line to a new file with the
lineinfile
module. The file can be created with.csv
extension, and in each line, the values are separated with delimiters (,
or ;
).
Here is an example:
---
- hosts: localhost
gather_facts: no
tasks:
- name: Read from CSV file
community.general.read_csv:
path: data.csv
key: empID
delimiter: ','
register: response
- name: Create a dict variable from the CSV file
set_fact:
data_dict: "{{ response.dict }}"
- name: Update values in dictionary recursively
set_fact:
data_dict: "{{ data_dict | combine(new_item, recursive=true) }}"
vars:
new_item: "{ '{{ item.key }}': { 'mark': 'some_value' } }"
with_dict: "{{ data_dict }}"
- name: Debug
debug:
msg: "{{ data_dict }}"
- name: Save ddata_dict headers to a new CSV file
lineinfile:
path: new_data.csv
line: empID,name,mark
create: yes
- name: Save data_dict values to a new CSV file
lineinfile:
path: new_data.csv
line: "{{ item.value.empID }},{{ item.value.name }},{{ item.value.mark }}"
loop: "{{ data_dict | dict2items }}"
And the outputted CSV file is:
empID,name,mark
111,user1,some_value
112,user2,some_value
113,user3,some_value