Search code examples
pythonoopkubernetesexportclone

Clone Kubernetes objects programmatically using the Python API


The Python API is available to read objects from a cluster. By cloning we can say:

  1. Get a copy of an existing Kubernetes object using kubectl get
  2. Change the properties of the object
  3. Apply the new object

Until recently, the option to --export api was deprecated in 1.14. How can we use the Python Kubernetes API to do the steps from 1-3 described above?

There are multiple questions about how to extract the code from Python API to YAML, but it's unclear how to transform the Kubernetes API object.


Solution

  • Just use to_dict() which is now offered by Kubernetes Client objects. Note that it creates a partly deep copy. So to be safe:

    copied_obj = copy.deepcopy(obj.to_dict())
    

    Dicts can be passed to create* and patch* methods.

    For convenience, you can also wrap the dict in Prodict.

    copied_obj = Prodict.from_dict(copy.deepcopy(obj.to_dict()))
    

    The final issue is getting rid of superfluous fields. (Unfortunately, Kubernetes sprinkles them throughout the object.) I use kopf's internal facility for getting the "essence" of an object. (It takes care of the deep copy.)

    copied_obj = kopf.AnnotationsDiffBaseStorage().build(body=kopf.Body(obj.to_dict()))
    copied_obj = Prodic.from_dict(copied_obj)