python k8s 实施
时间: 2024-01-21 07:15:21 浏览: 74
k8s(Kubernetes)是一个开源的容器编排平台,用于自动化部署、扩展和管理容器化应用程序。下面是一个使用Python实施k8s的示例:
1. 导入必要的Python库:
```python
from kubernetes import client, config
```
2. 配置k8s集群:
```python
config.load_kube_config() # 从kubeconfig文件加载配置
```
3. 创建k8s客户端:
```python
v1 = client.CoreV1Api()
```
4. 创建一个Pod:
```python
def create_pod():
pod_manifest = {
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "my-pod"
},
"spec": {
"containers": [
{
"name": "my-container",
"image": "nginx:latest",
"ports": [
{
"containerPort": 80
}
]
}
]
}
}
resp = v1.create_namespaced_pod(body=pod_manifest, namespace="default")
print("Pod created. status='%s'" % resp.status.phase)
```
5. 获取Pod列表:
```python
def get_pods():
pods = v1.list_namespaced_pod(namespace="default")
for pod in pods.items:
print(pod.metadata.name)
```
6. 删除Pod:
```python
def delete_pod():
resp = v1.delete_namespaced_pod(name="my-pod", namespace="default")
print("Pod deleted. status='%s'" % resp.status)
```
7. 调用上述函数来实施k8s:
```python
create_pod() # 创建一个Pod
get_pods() # 获取Pod列表
delete_pod() # 删除Pod
```
阅读全文