Akemi

Python yaml模块案例——提取与修改k8s配置文件

2024/11/09

(需要手动安装

让yaml模块与python对象之间进行格式装换,和json类似

常用方法

1.yaml.load
解析yaml格式为python对象

yaml.safe_load
安全解析

2.yaml.dump
将python对象序列化为yaml格式字符串

yaml.safe_dump
安全序列化

3.yaml.load_all
解析多个yaml文档

4.yaml.dump_add
将多个python对象序列化

提取k8s的yaml文件参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-v1
spec:
replicas: 2
selector:
matchLabels:
app: myapp
version: v1
template:
metadata:
labels:
app: myapp
version: v1
spec:
containers:
- name: myapp
image: janakiramm/myapp:v1
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
startupProbe:
periodSeconds: 5
initialDelaySeconds: 20
timeoutSeconds: 10
httpGet:
scheme: HTTP
port: 80
path: /
livenessProbe:
periodSeconds: 5
initialDelaySeconds: 20
timeoutSeconds: 10
httpGet:
scheme: HTTP
port: 80
path: /
readinessProbe:
periodSeconds: 5
initialDelaySeconds: 20
timeoutSeconds: 10
httpGet:
scheme: HTTP
port: 80
path: /
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#coding=utf-8
import yaml

# 查看deploy的信息
with open('deployment.yaml','r') as file:
config=yaml.safe_load(file)
# 打印出labels信息和image信息
app=config['spec']['template']['metadata']['labels']['app']
image=config['spec']['template']['spec']['containers'][0]['image']
print(f"app:{app}")
print(f"image:{image}")

# app:myapp
# image:janakiramm/myapp:v1

更换deploy文件镜像

1
2
3
4
5
6
7
8
9
10
11
12
#coding=utf-8
import yaml
def update_image(yaml_file,new_image):
with open(yaml_file,'r') as file:
config=yaml.safe_load(file)
# 替换image名
config['spec']['template']['spec']['containers'][0]['image']=new_image
with open(yaml_file,'w') as file:
yaml.safe_dump(config,file)

# 进行替换
update_image('deployment.yaml','janakiramm/myapp:v2')

从多个yaml文件中读取信息并统计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#coding=utf-8
import os
import yaml
report=[]
def extract_info(yaml_dir):
for yaml_file in os.listdir(yaml_dir):
if yaml_file.endswith('.yaml'):
with open(yaml_file,'r') as f:
config=yaml.safe_load(f)
service_name=config['metadata']['name']
image_version=config['spec']['template']['spec']['containers'][0]['image']
report.append(f"服务名称:{service_name},镜像版本:{image_version}")
return report
# 设置yaml路径
yaml_dir=os.getcwd()

#
extract_info(yaml_dir)
for line in report:
print(line)

# 服务名称:myapp-v2,镜像版本:janakiramm/myapp:v2
# 服务名称:myapp-v1,镜像版本:janakiramm/myapp:v1
CATALOG