Skip to content

Instantly share code, notes, and snippets.

@washraf
Created April 23, 2022 18:02
Show Gist options
  • Save washraf/f81153270c80b0b4ecf90a53872abde7 to your computer and use it in GitHub Desktop.
Save washraf/f81153270c80b0b4ecf90a53872abde7 to your computer and use it in GitHub Desktop.
Updating Values in Yaml File Dynamically
#!/usr/bin/env python3
# This is a simple way to edit/add values to a k8s configuration yaml file.
# This can be handy to test a change or to create a changes based on a policy outside the k8s stack.
import yaml
# I used yaml file available here https://raw.githubusercontent.com/kubernetes/website/main/content/en/examples/controllers/nginx-deployment.yaml
with open(f"deployment.yaml", "r") as stream:
try:
yaml_file = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
# You can do multiple types of updates.
# Change a value directly
yaml_file["spec"]["replicas"] = 5 # You can use any source for this input
# Change value inside a list
for container in yaml_file["spec"]["template"]["spec"]["containers"]:
if container["name"] == "nginx":
container["image"] = "nginx:latest"
# Add Values specific to this trial
yaml_file["spec"]["template"]["spec"]["containers"][0]["env"] = [{"name":"PASSWORD", "value": 'ADMIN'}]
print(yaml.dump(yaml_file))
# To run
# python3 gist.py | kubectl apply -f -
# To remove deployment
# python3 gist.py | kubectl delete -f -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment