Hướng dẫn update yaml file python - cập nhật tệp yaml python

The ruamel.yaml package was specifically enhanced (by me starting from PyYAML) to do this kind of round-trip, programmatic, updating.

If you start with (please note I removed the extra initial spaces):

init_config: {}
instances:
    - host:               # update with IP
      username:     # update with user name
      password:     # update with password

and run:

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)

The output will be:

init_config: {}
instances:
    - host: 1.2.3.4           # update with IP
      username: Username      # update with user name
      password: Password      # update with password

The ordering of mapping keys (

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
9,
init_config: {}
instances:
    - host: 1.2.3.4           # update with IP
      username: Username      # update with user name
      password: Password      # update with password
0 and
init_config: {}
instances:
    - host: 1.2.3.4           # update with IP
      username: Username      # update with user name
      password: Password      # update with password
1), the style and the comments are preserved without any further specific action.the comments are preserved without any further specific action.

Instead of having the indent and block sequence indent guessed, you can do a manual traditional load, and set the indent values yourself:

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=6, sequence=4)
with open(file_name) as fp:
    config = yaml.load(fp)

If you look at the history of this answer, you can see how to do this with a more limited, PyYAML like, API.

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. (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.

Nội dung chính ShowShow

  • 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.
  • Nội dung chính Show
  • Thông tin cơ bản:
  • Cú pháp cơ bản
  • Đọc 1 file YAML sử dụng ngôn ngữ lập trình
  • Đọc file YAML trong Perl
  • Đọc file YAML trong PHP
  • Đọc file YAML trong Python
  • Giới thiệu:

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.

  • Nội dung chính Show
  • Thông tin cơ bản:
  • Cú pháp cơ bản

Nội dung chính Show

Thông tin cơ bản:

# Programing Languages
- PHP
- Perl
- NodeJS

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

Cú pháp cơ bản

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

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

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

Đọc file YAML trong Perl

customer:
    first_name:   Dorothy
    family_name:  Gale

Thông tin cơ bản:

Cú pháp cơ bản

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

cpan YAML::XS

Đọc file YAML trong Perl

#!/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 1 file YAML sử dụng ngôn ngữ lập trình

Đọc file YAML trong Perl

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
0

Đọc file YAML trong PHP

  • symfony/yaml

Đọc file YAML trong Perl

Đọc file YAML trong PHP

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
1

Đọc file YAML trong Python

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
2

Giới thiệu:

1. Một số câu lệnh Jinja2: 2 phút đọc

Đọc file YAML trong PHP

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
3

Đọc file YAML trong Python

Giới thiệu: 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 }}

1. Một số câu lệnh Jinja2: 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 %}

2. Các bước thực hiện: 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 %}

Version mới nhất: 1.2 comment starts with ‘{#’ and ends with ‘#} example: {# set description only for interface ge-0/0/2 #}

Định dạng mở rộng: .yaml, .yml pip install jinja2 ( cho python 2.7 ) pip3 install jinja2 ( cho python > 3.6 )

Giới thiệu:

**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:

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
4

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:

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
5

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

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
6

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

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
7

Đọc yaml file trong Python

import ruamel.yaml

file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))

instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=ind, sequence=ind, offset=bsi) 
with open('output.yaml', 'w') as fp:
    yaml.dump(config, fp)
8

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