首页 > 解决方案 > 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)

            

标签: python-3.xyaml

解决方案


推荐阅读