How to use a multiple kubernetes resource file through kubernetes python client similar to kubectl apply -f

3/2/2020

I have a kubernetes multi-resource file which contains different resources that are to be applied for e.g. deployment-definition, service-defintion, pv, pvc etc. Is there any way to use this single file through kubernetes python client to deploy all these resources at once ? Though my scenario is a bit different. I have a file which use CRDs alongwith custom kubernetes resource objects for e.g. Deployment + ambassador's Mapping. How to achieve this using kubernetes python client?

-- Vedant Pareek
ambassador
kubectl
kubernetes
kubernetes-python-client

2 Answers

3/2/2020

With the client, you have to do them all separately. When you have multiple documents in a YAML file, kubectl just splits them for you and makes an API call for each.

-- coderanger
Source: StackOverflow

3/2/2020

I have a kubernetes multi-resource file Is there any way to use this single file through kubernetes python client to deploy all these resources at once ?

Please check the content of examples directory.

    from os import path

    import yaml

    from kubernetes import client, config


    def main():
        # Configs can be set in Configuration class directly or using helper
        # utility. If no argument provided, the config will be loaded from
        # default location.
        config.load_kube_config()

        with open(path.join(path.dirname(__file__), "nginx-deployment.yaml")) as f:
            dep = yaml.safe_load(f)
            k8s_beta = client.ExtensionsV1beta1Api()
            resp = k8s_beta.create_namespaced_deployment(
                body=dep, namespace="default")
            print("Deployment created. status='%s'" % str(resp.status))


    if __name__ == '__main__':
        main()

Important note: it's a must to use triple dashes at the top of your yaml file and in-between resources, if it contains more than one resource.

.../utils/create_from_yaml.py and .../examples/create_deployment_from_yaml.py are worth checking as well.

I have a file which use CRDs alongwith custom kubernetes resource objects

as @coderanger told, the example can be found in .../docs/CustomObjectsApi.md

Hope that helps.

-- Nick
Source: StackOverflow