日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Python教程 正文

python調用kubernetesAPI簡單使用方法_python

作者:低調說 ? 更新時間: 2022-07-15 Python教程

前言:

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多的類的對象。

原文鏈接:https://blog.csdn.net/hans99812345/article/details/124851132

欄目分類
最近更新