Hướng dẫn yaml python

YAML là gì?

YAML (YAML Ain’t Markup Language) là một chuẩn dữ liệu kiểu serialization dành cho tất cả các ngôn ngữ. Nó được sử dụng phổ biến để tạo ra các file config cho nhiều ứng dụng, VD: như Docker Compose.

Thông tin cơ bản:

  • Version mới nhất: 1.2
  • Định dạng mở rộng: .yaml, .yml
  • Tổ chức: yaml.org

Cú pháp cơ bản

Định nghĩa cấu trúc một danh sách (list) hay mảng (array)

# Programing Languages
- PHP
- Perl
- NodeJS

# Shopping list
[milk, pumpkin pie, eggs, juice]

Định nghĩa kiểu dữ liệu key-value

# Indented Block
name: Nguyen Van A
age: 33
# Inline Block
{name: Nguyen Van A, age: 33}

Định nghĩa ký tự dạng chuỗi, ký tự dạng chuỗi không yêu cầu dấu quote

data: |
   There once was a short man from Ealing
   Who got on a bus to Darjeeling
       It said on the door
       "Please don't spit on the floor"
   So he carefully spat on the ceiling

data: >
   Wrapped text
   will be folded
   into a single
   paragraph

   Blank lines denote
   paragraph breaks

Định nghĩa 1 đối tượng

customer:
    first_name:   Dorothy
    family_name:  Gale

Đọc 1 file YAML sử dụng ngôn ngữ lập trình

Đọc file YAML trong Perl

Sử dụng thư viện Perl có tên là YAML::XS để đọc bất kỳ file YAML nào. Để cài đặt module này các bạn sử dụng cài thông qua cpan

cpan YAML::XS

Đoạn code example, mà mình sử dụng để load 1 file config.yml

#!/usr/bin/perl
#
# Read YAML Config File by vinasupport.com
#

use strict;
use warnings;
use YAML::XS 'LoadFile';
use Data::Dumper;
    
my $config = LoadFile('config.yaml');
print Dumper($config);

Đọc file YAML trong PHP

Để đọc file yaml trong PHP, các bạn có thể sử dụng function yaml_parse_file được PHP hỗ trợ sẵn. Đoạn code example như bên dưới.

 'cb_yaml_date'));

print_r($data);

Ngoài ra PHP còn có rất nhiều thư viện bên ngoài như:

  • symfony/yaml

Đọc file YAML trong Python

Trong Python, để đọc file yaml thì chúng ta cài đặt thư viện PyYAML thông qua pip3

pip3 install PyYAML

Đoạn sample code đọc yaml trong Python 3

#!/usr/bin/env python3
import yaml

with open("configs.yaml", 'r') as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as error:
        print(error)

Nguồn: vinasupport.com

Hướng dẫn yaml python

Đã đăng vào thg 1 3, 2019 5:27 SA 2 phút đọc

Giới thiệu:

Jinja2 is a powerful templating language for Python. If you are in network automation business you are going to love it I guarantee it. Using Jinja2 you can build a template which uses variables instead of hard coded values, Jinja2 then automagically renders template using variable values. Variable values either comes from Python dictionary or yaml file. Jinja2 also allows you to add control statements like ‘for’ loop & ‘If’ statement to create logic in template file.

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 }}

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 %}

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 %}

Comment: 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 )

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:


{% for interface in interfaces %}
     {{interface}} 
          {{description}} 
     
{% endfor %}

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:

$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import jinja2
>>> import yaml
>>> import os
>>> from lxml import etree
>>> templateFilePath = jinja2.FileSystemLoader(os.getcwd())
>>> jinjaEvn = jinja2.Environment(loader=templateFilePath, trim_blocks=True, lstrip_blocks=True)
>>> jTemplate = jinjaEvn.get_template('interfaces.j2')
>>> config = {
...         'interfaces' : ['ge-0/0/1', 'ge-0/0/2', 'ge-0/0/3'], 
...         'description': 'interface configured using jinja2 template'
...     }
>>> print(jTemplate.render(config))

      ge-0/0/1 
           interface configured using jinja2 template 
      
      ge-0/0/2 
           interface configured using jinja2 template 
      
      ge-0/0/3 
           interface configured using jinja2 template 
      

>>> 

Ngoài ra bạn có thể render bằng cách sau:

>>> print(jTemplate.render(
...         interfaces={'ge-0/0/1', 'ge-0/0/2', 'ge-0/0/3'}, 
...         description= 'interface configured using jinja2 template'
...         ))

      ge-0/0/2 
           interface configured using jinja2 template 
      
      ge-0/0/1 
           interface configured using jinja2 template 
      
      ge-0/0/3 
           interface configured using jinja2 template 
      

>>> 

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ình

---
interfaces:
- ge-0/0/1
- ge-0/0/2
- ge-0/0/3
description:
 "configured by using jinja2 & yaml"

Đọc yaml file trong Python

>>> templateVars = yaml.load(open('interfaces.yaml').read())
>>> print(jTemplate.render(templateVars))

      ge-0/0/1 
           configured by using jinja2 & yaml 
      
      ge-0/0/2 
           configured by using jinja2 & yaml 
      
      ge-0/0/3 
           configured by using jinja2 & yaml 
      

>>> 

Vậy là đến đây bạn đã biết sử dụng Jinja2 template - Yaml File - Python cho network automation.

Tham Khảo:

  • Welcome to Jinja2: http://jinja.pocoo.org/docs/dev/
  • Lab-10:Python for network automation -using Jinja2 template and YAML file: https://sunnynetwork.wordpress.com/2016/03/17/lab-10jinja2-template-and-yaml-file/

All rights reserved