I'm using ansible to convert CSV file to YML
CSV file
Ansible Playbook
---
- hosts: localhost
connection: local
gather_facts: false
become: false
vars:
csvfile: "{{ lookup('file', 'test.csv') }}"
tasks:
- name: Parse CSV To YAML
template:
src: "./iterate_csv_test.j2"
dest: "./test.yml"
run_once: true
Jinja2 file "iterate_csv_test.j2"
nodes:
{% for row in csvfile.split('\n') %}
{% if loop.index != 1 %}
{% set list = row.split(',') %}
{{list[0]}}:
interfaces:
{{list[1]}}: {nbr: '{{list[2]}}', nbr_int: '{{list[3]}}'}
{% endif %}
{% endfor %}
The Output test.yml
nodes:
Router1:
interfaces:
xe-1/0/0: {nbr: 'Router3', nbr_int: 'xe-0/0/4'}
Router1:
interfaces:
xe-1/0/1: {nbr: 'Router4', nbr_int: 'xe-0/0/10'}
Router2:
interfaces:
xe-1/0/2: {nbr: 'Router3', nbr_int: 'xe-3/0/5'}
Router2:
interfaces:
xe-3/0/0: {nbr: 'Router4', nbr_int: 'xe-0/1/4'}
So now I have my test.yml file generated from CSV file, and as shown node is repeated two times as in CSV file, However I need all interfaces for same node to be grouped under this node to be look like
nodes:
Router1:
interfaces:
xe-1/0/0: {nbr: 'Router3', nbr_int: 'xe-0/0/4'}
xe-1/0/1: {nbr: 'Router4', nbr_int: 'xe-0/0/10'}
Router2:
interfaces:
xe-1/0/2: {nbr: 'Router3', nbr_int: 'xe-3/0/5'}
xe-3/0/0: {nbr: 'Router4', nbr_int: 'xe-0/1/4'}
So , I modified Jinja2 code to below, But it gives me same result. So can you help me to do this job
nodes:
{% set curr_node = 'none' %}
{% for row in csvfile.split('\n') %}
{% if loop.index != 1 %}
{% set list = row.split(',') %}
{% set new_node = list[0] %}
{% if new_node != curr_node %}
{{list[0]}}:
interfaces:
{{list[1]}}: {nbr: '{{list[2]}}', nbr_int: '{{list[3]}}'}
{% elif new_node == curr_node %}
{{list[1]}}: {nbr: '{{list[2]}}', nbr_int: '{{list[3]}}'}
{% endif %}
{% set curr_node = new_node %}
{% endif %}
{% endfor %}
Comments
Post a Comment