How do you apply a YAML manifest from Python?
AdvancedConceptKubernetes, Docker & SSH clients
Answer
kubernetes.utils.create_from_yaml(api_client, "app.yaml") creates objects but does not update existing ones (409 Conflict). For apply semantics, use server-side apply through the dynamic client:
from kubernetes import dynamic
dyn = dynamic.DynamicClient(client.ApiClient())
for doc in yaml.safe_load_all(open("app.yaml")):
api = dyn.resources.get(api_version=doc["apiVersion"], kind=doc["kind"])
api.server_side_apply(body=doc, namespace=doc["metadata"].get("namespace", "default"),
field_manager="ops-bot", force_conflicts=True)
Many teams simply call kubectl apply via subprocess for this, which is acceptable and easier to reason about.
More on Kubernetes, Docker & SSH clients
How does the official Kubernetes Python client authenticate?BeginnerHow do you list pods with high restart counts using the Python client?BeginnerHow do you patch or scale a Deployment with the Python client?IntermediateHow does `watch.Watch()` work, and what is a `410 Gone`?AdvancedHow do you use the Docker SDK for Python?BeginnerHow do you clean up dangling Docker images and stopped containers with Python?Intermediate