python-3.x - Yaml 嵌套替换 python 中的所有列表、映射和字符串值
问题描述
我正在尝试在 yaml 中查找特定值并希望全部替换。我能够替换所有但无法添加为嵌套值。
示例:能够识别 - 根键 ['selector', 'matchLabels'] 匹配键:matchLabels 值:<> 替换值:[{'app':'testservice','team':'testing','contact':' test@contact.com'}]
在我的 Yaml 中: new_dict['selector']['matchLabels']=replacevalue 我得到 new_dict['matchLabels']=replacevalue
试过: if (len(rootkey) ==2): new_dict[rootkey[0]][rootkey[1]]=replacevalue // 这不起作用
任何帮助都将节省时间,因为我是 python 新手。
这是我的数据文件
appname: testservice
imagerepopath: saradaimage
labels:
- app: testservice
team: testing #mandatory
contact: test@contact.com #mandatory
这是我的 yaml 模板
apiVersion: apps/v1
kind: Deployment
metadata:
name: <<appname>>
labels:
<<labels>>
spec:
replicas: <<replicas>>
selector:
matchLabels:
<<labels>>
minReadySeconds: 10
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
type: RollingUpdate
template:
metadata:
labels:
<<labels>>
spec:
containers:
image: <<imagerepopath>>
imagePullPolicy: IfNotPresent
name: accountservice
ports:
- containerPort: <<port>>
resources:
limits:
cpu: '1'
memory: 2Gi
status: {}
我的 Python 能够识别字段但不能替换嵌套的值:
import yaml
import os
from collections import defaultdict
yaml.Dumper.ignore_aliases = lambda *args : True
deploymentName = "templates/deploymenttemplate.yaml"
dataName = "k8sdata.yaml"
rootkey = []
def parseYaml(fname):
stream = open(fname, 'r')
return yaml.safe_load(stream)
def nested_dict_pairs_iterator(dict_obj,currentvalue,replacevalue):
global rootkey
# Iterate over all key-value pairs of dict argument
for key, value in dict_obj.items():
rootkey.append(key)
# Check if value is of dict type
if isinstance(value, dict):
# If value is dict then iterate over all its values
for pair in nested_dict_pairs_iterator(value,currentvalue,replacevalue):
yield (key, *pair)
else:
# If value is not dict type then yield the value
print("root key",rootkey)
if (value == currentvalue) :
print ("match key : ",key," value : ",currentvalue, " replacevalue : ",replacevalue )
new_dict[key] = replacevalue
else :
print ("Unmatch key : ",key," value : ",value )
new_dict[key] = value
rootkey = []
yield (key, value)
def updateDeployment(dataf):
for datakey, datavalue in dataf.items():
actualvalue = "<<"+datakey+">>"
for pair in nested_dict_pairs_iterator(deploymentf,actualvalue,datavalue):
print("---------------------------------------------")
print(new_dict)
with open('temp/data.yml', 'w') as outfile:
yaml.dump(new_dict, outfile,sort_keys=False,default_flow_style=False)
dataF = parseYaml(dataName)
deploymentf = parseYaml(deploymentName)
new_dict = defaultdict(dict)
updateDeployment(dataF)
解决方案
推荐阅读
- swift - '属性实现必须在'TestingAdditions'类别中声明是什么意思?
- c - 结构中的指针如何在以下代码中工作?
- python - Telegram 将 csv 文件中的抓取用户从特定行添加到特定行
- python - 如果列表中存在特定列,有没有办法对它们求和?
- git - 在 git merge 上用字符串替换标记
- python - python海龟波动写什么错?
- asp.net-core - 锚标记助手未生成区域名称为 MVC Core 3.1 的正确路由
- ios - 使用flurry api的api请求IOS
- c# - 如何调整此代码以使用 getter/setter?
- flutter - 警告:此应用程序的语言环境 en.json_US 并非所有本地化代表都支持