简体   繁体   中英

Editing YAML file by Python and ruamel.yaml module

I need to edit this yaml file changing cpu and memory variable. I'm a begginer python developer.

I'm using python 3, and ruamel.yaml with sys module.

The yaml to change:

- 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

Here is my code:

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) 

The output of my code is:

  -   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

What am I doing wrong?

Thanks, Regards!

YAML is a hierarchical structure. When you read it, that hierarchy is preserved. Your code accesses a 2nd level element (kind), and that works as you expect. But the elements you want to change are on deeper nesting levels. Your code tries to modify them at the wrong level. Don't modify child elements of elem , but go all the way down the hierarchy:

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) 

This replaces the CPU item in spec.hard.cpu. Adjust for the other cpu entries as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM