python調用kubernetesAPI簡單使用方法
前言:
K8s也提供API接口,提供這個接口的是管理節點的apiserver組件,apiserver服務負責提供HTTP API,以便用戶、其他組件相互通信。客戶端庫
安裝
pip install kubernetes -i https://pypi.douban.com/simple
k8s認證方式:
- HTTPS 證書認證:基於CA證書簽名的數字證書認證
- HTTP Token認證:通過一個Token來識別用戶
HTTPS證書認證(kubeconfig)
import os from kubernetes import client, config config.load_kube_config(file_path) # 指定kubeconfig配置文件 apps_api = client.AppsV1Api() # 資源接口類實例化 for dp in apps_api.list_deployment_for_all_namespaces().items: print(dp)
HTTP Token認證(ServiceAccount)
from kubernetes import client, config configuration = client.Configuration() configuration.host = "https://192.168.3.201:16443" # APISERVER地址 configuration.ssl_ca_cert="ca.crt" # CA證書 /etc/kubernetes/pki/ca.crt configuration.verify_ssl = True # 啟用證書驗證 configuration.api_key = {"authorization": "Bearer " + token} # 指定Token字符串 client.Configuration.set_default(configuration) apps_api = client.AppsV1Api()
這2個認證,2選1
獲取Token字符串:創建service account並綁定默認cluster-admin管理員集群角色:
創建用戶:
$ kubectl create serviceaccount dashboard-admin -n kube-system
用戶授權:
$ kubectl create clusterrolebinding dashboard-admin –clusterrole=cluster-admin –serviceaccount=kube-system:dashboard-admin
獲取用戶Token:
$ kubectl describe secrets -n kube-system $(kubectl -n kube-system get secret | awk ‘/dashboard-admin/{print $1}’)
其他常用資源接口類實例化:
core_api = client.CoreV1Api() # namespace,pod,service,pv,pvc apps_api = client.AppsV1Api() # deployment networking_api = client.NetworkingV1beta1Api() # ingress storage_api = client.StorageV1Api() # storage_class
舉個例子
Deployment操作:
# 先得有上面的認證,下面的代碼才行 # 創建 namespace = "default" name = "api-test" replicas = 3 labels = {'nginx':'true'} # 不區分數據類型,都要加引號 image = "nginx" body = client.V1Deployment( api_version="apps/v1", kind="Deployment", metadata=client.V1ObjectMeta(name=name), spec=client.V1DeploymentSpec( replicas=replicas, selector={'matchLabels': labels}, template=client.V1PodTemplateSpec( metadata=client.V1ObjectMeta(labels=labels), spec=client.V1PodSpec( containers=[client.V1Container( name="web", image=image )] ) ), ) ) try: apps_api.create_namespaced_deployment(namespace=namespace, body=body) except Exception as e: status = getattr(e, "status") if status == 400: print(e) print("格式錯誤") elif status == 403: print("沒權限") # 刪除 name = "api-test" apps_api.delete_namespaced_deployment(namespace=namespace, name=name)
但其實這個API挺繞的 ,一個創建deployment的,這裡N多的類的對象。
到此這篇關於python調用kubernetesAPI簡單使用方法的文章就介紹到這瞭,更多相關python調用kubernetesAPI 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- K8S 中 kubectl 命令詳解
- python3 kubernetes api的使用示例
- Python使用Kubernetes API訪問集群
- k8s中pod使用詳解(雲原生kubernetes)
- Kubernetes中創建命名空間實現方法