<p>My Bash script using <code>kubectl create/apply -f ...</code> to deploy lots of Kubernetes resources has grown too large for Bash. I'm converting it to Python using the PyPI <code>kubernetes</code> package.</p>

<p>Is there a generic way to create resources given the YAML manifest? Otherwise, the only way I can see to do it would be to create and maintain a mapping from Kind to API method <code>create_namespaced_&lt;kind&gt;</code>. That seems tedious and error prone to me.</p>

<p>Update: I'm deploying many (10-20) resources to many (10+) GKE clusters.</p>

<p>I have written a following piece of code to achieve the functionality of creating k8s resources from its json/yaml file:</p>

<pre><code>def create_from_yaml(yaml_file):
    """

    :param yaml_file:
    :return:
    """

    yaml_object = yaml.loads(common.load_file(yaml_file))
    group, _, version = yaml_object["apiVersion"].partition("/")
    if version == "":
        version = group
        group = "core"

    group = "".join(group.split(".k8s.io,1"))
    func_to_call = "{0}{1}Api".format(group.capitalize(), version.capitalize())

    k8s_api = getattr(client, func_to_call)()

    kind = yaml_object["kind"]
    kind = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', kind)
    kind = re.sub('([a-z0-9])([A-Z])', r'\1_\2', kind).lower()

    if "namespace" in yaml_object["metadata"]:
        namespace = yaml_object["metadata"]["namespace"]
    else:
        namespace = "default"

    try:
        if hasattr(k8s_api, "create_namespaced_{0}".format(kind)):
            resp = getattr(k8s_api, "create_namespaced_{0}".format(kind))(
                body=yaml_object, namespace=namespace)
        else:
            resp = getattr(k8s_api, "create_{0}".format(kind))(
                body=yaml_object)
    except Exception as e:
        raise e

    print("{0} created. status='{1}'".format(kind, str(resp.status)))

    return k8s_api
</code></pre>

<p>In above function, If you provide any object yaml/json file, it will automatically pick up the API type and object type and create the object like statefulset, deployment, service etc.</p>

<p>PS: The above code doesn't handler multiple kubernetes resources in one file, so you should have only one object per yaml file.</p>
