我需要编辑此yaml文件,以更改cpu和内存变量。我是一名初学者python开发人员。
我正在将python 3和ruamel.yaml用于sys模块。
要更改的Yaml:
- apiVersion: v1
kind: ResourceQuota
metadata:
annotations:
openshift.io/quota-tier: Medium
creationTimestamp:
labels:
quota-tier: Medium
name: burst-quota
namespace: testing
resourceVersion: ""
selfLink: /api/v1/namespaces/testing/resourcequotas/burst-quota
uid:
spec:
hard:
cpu: "8"
memory: 16Gi
status:
hard:
cpu: "8"
memory: 16Gi
used:
cpu: 20m
memory: 256Mi
这是我的代码:
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open('quota-edit.yaml') as fp:
data = yaml.load(fp)
for elem in data:
if elem['kind'] == 'ResourceQuota':
elem['spec'] = None
elem['hard'] = None
elem['cpu'] = 123
break
yaml.dump(data, sys.stdout)
我的代码输出是:
- apiVersion: v1
kind: ResourceQuota
metadata:
annotations:
openshift.io/quota-tier: Medium
creationTimestamp:
labels:
quota-tier: Medium
name: burst-quota
namespace: sre
resourceVersion: ""
selfLink: /api/v1/namespaces/testing/resourcequotas/burst-quota
uid:
spec:
hard:
cpu: '8'
memory: 16Gi
status:
hard:
cpu: '8'
memory: 16Gi
used:
cpu: 20m
memory: 256Mi
cpu: 123
我做错了什么?
谢谢,问候!
YAML是一个层次结构。当您阅读它时,将保留该层次结构。您的代码访问第二级元素(种类),并且可以按预期工作。但是要更改的元素位于更深的嵌套级别。您的代码尝试在错误的级别上对其进行修改。不要修改elem
的子元素,但要一直沿层次进行下去:
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open('quota-edit.yaml') as fp:
data = yaml.load(fp)
for elem in data:
if elem['kind'] == 'ResourceQuota':
elem['spec']['hard']['cpu'] = 123
break
yaml.dump(data, sys.stdout)
这将替换spec.hard.cpu中的CPU项目。根据需要调整其他cpu条目。