如何从给定预定义CSV文件解析生成条件Jinja模板
Got it, let's break down how to turn your CSV network data into a conditional Jinja template. We'll use Python (super flexible for this automation) with its built-in csv module and the Jinja2 templating engine—perfect for handling conditional logic based on your CSV fields.
Step 1: Define Your Conditional Jinja Template
First, create a Jinja template file (let's call it network_config.j2) that uses your CSV fields to render configs with conditionals. We'll branch logic based on routed (to decide if we generate routing config) and gateway_name (to tailor config for different devices):
{% for entry in network_entries %} ### VLAN {{ entry.vlan_id }} - *{{ entry.description }}* {% if entry.routed.lower() == 'yes' %} interface Vlan{{ entry.vlan_id }} ip address {{ entry.network }} {{ entry.mask }} ip route {{ entry.network }} {{ entry.mask }} {{ entry.gateway }} {% if entry.gateway_name == 'localL3_switch' %} ! Gateway: Local Layer 3 Switch ip helper-address {{ entry.gateway }} {% elif entry.gateway_name == 'local_ASA_Fw' %} ! Gateway: Local ASA Firewall ip access-group INTERNAL_IN in {% else %} ! Gateway: {{ entry.gateway_name }} (custom config here) {% endif %} {% else %} ! VLAN {{ entry.vlan_id }} is **not routed** {% endif %} {% endfor %}
Step 2: Python Script to Parse CSV & Render Template
Next, write a Python script that reads your CSV, maps each row to a dictionary, and feeds the data into the Jinja template. This handles the data parsing and template rendering in one go:
import csv from jinja2 import Environment, FileSystemLoader # Load CSV data into a list of dictionaries network_entries = [] with open('your_networks.csv', 'r') as csv_file: # DictReader uses CSV headers as dictionary keys csv_reader = csv.DictReader(csv_file) for row in csv_reader: # Optional: Convert vlan_id to integer for cleaner template output row['vlan_id'] = int(row['vlan_id']) network_entries.append(row) # Set up Jinja2 environment and load the template env = Environment(loader=FileSystemLoader('.')) # Looks for templates in current directory template = env.get_template('network_config.j2') # Render the template with our CSV data rendered_output = template.render(network_entries=network_entries) # Save or print the result print(rendered_output) with open('final_network_config.txt', 'w') as output_file: output_file.write(rendered_output)
Key Notes & Optimizations
- CSV Handling:
csv.DictReaderautomatically maps each CSV row to a dictionary using your headers (vlan_id,network, etc.), so you don't have to manually index columns. - Conditional Logic: The template uses
{% if %}blocks to checkroutedstatus andgateway_namevalues—easy to extend if you add more gateway types later. - IP Address Helpers: If you need to manipulate IPs (like calculating subnets), install the
jinja2-ipaddrpackage and use Jinja'sipaddrfilters (e.g.,{{ entry.network | ipaddr('broadcast') }}). - Error Handling: For robustness, you could add checks for missing fields or invalid IPs (using Python's
ipaddressmodule) before rendering.
Test with Your Sample Data
If you run this with your provided CSV data, the output will generate tailored configs:
- VLAN 2 (gateway:
localL3_switch) gets helper-address config - VLANs 3/4 (gateway:
local_ASA_Fw) get access-group config - Any VLAN with
routed=nowill skip routing config
内容的提问来源于stack exchange,提问作者Raghuprasad Gundeti

