I have the following YAML file:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nodejs
namespace: test
labels:
app: hello-world
spec:
selector:
matchLabels:
app: hello-world
replicas: 100
template:
metadata:
labels:
app: hello-world
spec:
containers:
- name: hello-world
image: test/first:latest
ports:
- containerPort: 80
resources:
limits:
memory: 2500Mi
cpu: "2500m"
requests:
memory: 12Mi
cpu: "80m"
---
apiVersion: v1
kind: Service
metadata:
name: nodejs
spec:
selector:
app: hello-world
ports:
- protocol: TCP
port: 80
targetPort: 80
nodePort: 30082
type: NodePort
I need to edit the YAML file using Python, I have tried the code below but it is not working for a file with multiple YAML documents. you can see the below image:
import ruamel.yaml
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.explicit_start = True
with open(r"D:\deployment.yml") as stream:
data = yaml.load_all(stream)
test = data[0]['metadata']
test.update(dict(name="Tom1"))
test.labels(dict(name="Tom1"))
test = data['spec']
test.update(dict(name="sfsdf"))
with open(r"D:\deploymentCopy.yml", 'wb') as stream:
yaml.dump(data, stream)
you can refer the link for more info : Python: Replacing a String in a YAML file