基础知识
平时大家都习惯于使用kubectl命令行工具,对k8s集群进行控制。kubectl底层其实是对kube-apiserver进行http访问,再由kube-apiserver统一控制Kubernetes 。
本文介绍的kubernetes包其实就是将对kube-apiserver的http访问封装成python可用的对象。
安装
From source:
git clone --recursive https://github.com/kubernetes-client/python.git
cd python
python setup.py install
From PyPI directly:
pip install kubernetes
初始化
首先引入SDK支持库。然后将 ~/.kube 的config文件的内容复制到本地目录,保存为文件kubeconfig.yaml,然后运行下面的python代码:
from kubernetes import client, config
config.kube_config.load_kube_config(config_file="kubeconfig.yaml")
Examples
1、 创建namespace
api_v1_instance = client.CoreV1Api()
ns = client.V1Namespace()
ns.metadata = client.V1ObjectMeta(name="test-ns")
api_v1_instance.create_namespace(body=ns)
2、创建pod, 例子参考kubernetes官网
##方式一 使用封装的对象
pod = client.V1Pod()
pod.metadata = client.V1ObjectMeta(name='memory-demo')
container = client.V1Container(name='memory-demo-ctr', image='polinux/stress')
container.resources = client.V1ResourceRequirements(
limits={
"memory": "200Mi"
},
requests={
"memory": "100Mi"
}
)
container.command = ["stress"]
container.args = ["--vm", "1", "--vm-bytes", "150M", "--vm-hang", "1"]
spec = client.V1PodSpec(containers=[container])
pod.spec = spec
api_v1_instance = client.CoreV1Api()
api_v1_instance.create_namespaced_pod(namespace='test-ns', body=pod)
##方式二 使用字典形式
body = {
'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {
'name': 'memory-demo',
'namespace': 'test-ns'
},
'spec': {
'containers': [{
'name': 'memory-demo-ctr',
'image': 'polinux/stress',
'resources': {
'limits': {
'memory': '200Mi'
},
'requests': {
'memory': '100Mi'
}
},
'command': ["stress"],
'args': ["--vm", "1", "--vm-bytes", "150M", "--vm-hang", "1"]
}]
}
}
api_v1_instance = client.CoreV1Api()
api_v1_instance.create_namespaced_pod(namespace='test-ns', body=body)
3、创建Deployment
body = {
'apiVersion': 'apps/v1beta2',
'metadata': {'labels': {'app': 'test-app'},
'namespace': 'test-ns',
'name': 'test-dm'},
'kind': 'Deployment',
'spec': {
'replicas': 1,
.....省略
}
}
api_v1beta2_instance = kubernetes.client.AppsV1beta2Api()
api_v1beta2_instance.create_namespaced_deployment(namespace='test-ns', body=body)
网友评论