Kubernetes Python Api Client: Execute Full Yaml File
Kubernetes has a very nice official Python API client. The API client assumes that you will be creating individual resources (such as pods, or services) and assumes that you will b
Solution 1:
You can try using create_from_yaml
provided by kubernetes.utils in the following way.
This is the multi-resource-definition file
apiVersion:v1kind:Podmetadata:name:nginx-podlabels:app:nginxspec:containers:-name:ngnx-containerimage:nginx:latestports:-containerPort:80---apiVersion:v1kind:Servicemetadata:name:nginx-servicespec:selector:app:nginxports:-port:8080targetPort:80
Now you can try running the below code and check whether that works out for you or not.
from kubernetes import client, config, utils
config.load_kube_config()
k8s_client = client.ApiClient()
yaml_file = '<location to your multi-resource file>'
utils.create_from_yaml(k8s_client, yaml_file)
Solution 2:
There appears to be examples of this in the examples
directory. In particular https://github.com/kubernetes-client/python/blob/6709b753b4ad2e09aa472b6452bbad9f96e264e3/examples/create_deployment_from_yaml.py which does:
from os import path
import yaml
from kubernetes import client, config
defmain():
# 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()
withopen(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()
Solution 3:
In addition to what others have recommended, you can do this with Hikaru'sload_full_yaml
.
What's nice about Hikaru is that:
- It's object oriented and Pythonic with functions like
Pod.create()
. - It's autogenerated from the OpenAPI spec so nothing is missing
I evaluated at least five different Kubernetes libraries when building my own open source Python Kubernetes platform and Hikaru was by far the easiest to use.
Post a Comment for "Kubernetes Python Api Client: Execute Full Yaml File"