Hướng dẫn python dict template - mẫu python dict
Đã đăng vào thg 1 3, 2019 5:27 SA 2 phút đọc 2 phút đọc Giới thiệu:
1. Một số câu lệnh Jinja2:Variable: biến bắt đầu với {{ tên biến và kết thúc với }} example: tạo biến có tên interface {{ interface }} biến bắt đầu với {{ tên biến và kết thúc với }} example: tạo biến có tên interface {{ interface }} For loop: câu lệnh for bắt đầu với {% for statement %} và kết thúc với {% end %} example: {% for interface in interfaces %} … {% endfor %} câu lệnh for bắt đầu với {% for statement %} và kết thúc với {% end %} example: {% for interface in interfaces %} … {% endfor %} If statement: Câu lệnh if bắt đầu với {% if statement %} và kết thúc với {% endif %} example: {% if interface == ‘ge-0/0/2’ %} … {% endif %} Câu lệnh if bắt đầu với {% if statement %} và kết thúc với {% endif %} example: {% if interface == ‘ge-0/0/2’ %} … {% endif %} Comment: comment starts with ‘{#’ and ends with ‘#} example: {# set description only for interface ge-0/0/2 #} comment starts with ‘{#’ and ends with ‘#} example: {# set description only for interface ge-0/0/2 #} Cài đặt: pip install jinja2 ( cho python 2.7 ) pip3 install jinja2 ( cho python > 3.6 ) pip install jinja2 ( cho python 2.7 ) pip3 install jinja2 ( cho python > 3.6 ) 2. Các bước thực hiện:**Bước-1: ** Tạo file Jinja2 template với tên interfaces.j2. Thêm nội dung vào file interfaces.j2, ở đây tôi tạo một mẫu xml nhưng nó có thể là bất kì format:
Bước-2: mở terminal hoặc command-line và start python ( ở đây tôi đang dùng terminal trên Linux ), Import packages, set environment và load jinja2 template: mở terminal hoặc command-line và start python ( ở đây tôi đang dùng terminal trên Linux ), Import packages, set environment và load jinja2 template:
Ngoài ra bạn có thể render bằng cách sau:
Bước-3: Bạn có thể configuration đến file thay cho biến config ở trên để khi cần thay đổi không phải vào sửa lại code: Tạo interfaces.yaml file để lưu lại các thông tin cấu hìnhinterfaces.yaml file để lưu lại các thông tin cấu hình
Đọc yaml file trong Python
Vậy là đến đây bạn đã biết sử dụng Jinja2 template - Yaml File - Python cho network automation. Tham Khảo:
All rights reserved |