Say, I want to dynamically edit a Kubernetes deployment file that looks like this using Python:
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
replicas: 4
selector:
matchLabels:
app: guestbook
tier: frontend
template:
metadata:
labels:
app: guestbook
tier: frontend
spec:
containers:
- env:
- name: GET_HOSTS_FROM
value: dns
image: gcr.io/google-samples/gb-frontend:v4
name: php-redis
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 100Mi
I have a code that opens this yaml file where I want to change the content of spec.replicas branch from 2 to 4:
with open(deployment_yaml_full_path, "r") as stream:
try:
deployment = yaml.safe_load(stream)
if value_to_change[0] == 'spec.replicas':
deployment['spec']['replicas'] = value_to_change[1]
except yaml.YAMLError as exc:
logger.error('There was a problem opening a deployment file in path: ',
deployment_yaml_full_path=deployment_yaml_full_path, exc=exc)
I would like to know if there's a way to avoid the hardcoded part here to something more dynamic:
if value_to_change[0] == 'spec.replicas':
deployment['spec']['replicas'] = value_to_change[1]
Is there a way?