Creating Static Configuration Template with jinja2

membuat konfigurasi perangkat jaringan melelahkan jika kita membuatnya satu persatu. alangkah baiknya dilakukan dengan cara lain yaitu menggunakan python dengan jinja2 template. yang pertama harus dilakukan adalah membuat template jinja2 (template.j2) :

set system host-name {{ hostname }}
{% for interface in interface_list.ethernet %}
set interface {{ interface.type }} {{ interface.name }} address {{ interface.address}}
set interface {{ interface.type }} {{ interface.name }} description "{{ interface.description }}"
{% endfor %}

setelah itu, buat file inventory yang akan diisikan (inventory.yaml) :

system:
  hostname: "R1"
interface:
  ethernet:
    - name: "eth0"
      address: "192.168.1.1/24"
      description: "Ethernet0 Configuration"
      type: "ethernet"
    - name: "eth1"
      address: "192.168.2.1/24"
      description: "Ethernet1 Configuration"
      type: "ethernet"

lalu buat script pythonnya :

import yaml
from jinja2 import Environment, FileSystemLoader

# open json and read into raw text
raw = open('inventory.yaml').read()
 
# loads the raw into loads() function to create dict
data = yaml.load(raw)

# Set environment jinja2 in current folder
ENV = Environment(loader=FileSystemLoader('.'))

# get template from jinja2
template = ENV.get_template("template.j2")

# parse and print template jinja2 with variable from yaml
print(template.render(hostname=data["system"]["hostname"],interface_list=data["interface"]))

setelah itu coba jalankan script pythonnya :

zufar@zufar:~/Documents/Technology/Programming/Python/configuration$ python program.py
set system host-name R1

set interface ethernet eth0 address 192.168.1.1/24
set interface ethernet eth0 description "Ethernet0 Configuration"

set interface ethernet eth1 address 192.168.2.1/24
set interface ethernet eth1 description "Ethernet1 Configuration"

zufar@zufar:~/Documents/Technology/Programming/Python/configuration$

Comments are closed.