使用 Python 為 Google Kubernetes Engine (GKE) 建置 Kubernetes 用戶端
這篇部落格文章介紹了一種使用 Python 為 GKE 建立 Kubernetes 客戶端的有效方法。透過利用 google-cloud-container、google-auth 和 kubernetes 庫,無論您的應用程式是在本地運行還是在 Google Cloud 上運行,您都可以使用相同的程式碼與 Kubernetes API 進行互動。這種靈活性來自於使用應用程式預設憑證(ADC)來驗證和動態建立 Kubernetes API 互動所需的請求,從而無需使用額外的工具或設定檔(如 kubeconfig)。
本地運行時,常見的方法是使用 gcloud 容器叢集 get-credentials 命令產生 kubeconfig 檔案並使用 kubectl 與 Kubernetes API 互動。雖然此工作流程對於本機設定來說是自然且有效的,但在 Cloud Run 或其他 Google Cloud 服務等環境中卻變得不太實用。
借助 ADC,您可以透過動態配置 Kubernetes 用戶端來簡化對 GKE 叢集的 Kubernetes API 的存取。這種方法可確保以一致、高效的方式連接到集群,而無需管理外部設定檔或安裝額外工具的開銷。
先決條件
1. 使用 Google Cloud 進行身份驗證
如果您在本地運行程式碼,只需使用以下命令進行身份驗證:
gcloud auth application-default login
這將使用您的使用者帳戶憑證作為應用程式預設憑證(ADC)。
如果您在 Cloud Run 等 Google Cloud 服務上執行程式碼,則無需手動處理驗證。只需確保服務具有正確配置的服務帳戶,並具有存取 GKE 叢集所需的權限。
2. 收集您的集群詳細信息
運行腳本之前,請確保您了解以下詳細資訊:
- Google Cloud 專案 ID:託管 GKE 叢集的專案的 ID。
- 群集位置:群集所在的區域或可用區(例如 us-central1-a)。
- 叢集名稱:您要連接的 Kubernetes 叢集的名稱。
腳本
以下是為 GKE 叢集設定 Kubernetes 用戶端的 Python 函數。
gcloud auth application-default login
它是如何運作的
1. 連接GKE集群
get_k8s_client 函數首先使用 google-cloud-container 函式庫從 GKE 取得叢集詳細資訊。此程式庫與 GKE 服務交互,可讓您檢索叢集的 API 端點和憑證授權單位 (CA) 等資訊。這些詳細資訊對於配置 Kubernetes 客戶端至關重要。
from google.cloud import container_v1 import google.auth import google.auth.transport.requests from kubernetes import client as kubernetes_client from tempfile import NamedTemporaryFile import base64 import yaml def get_k8s_client(project_id: str, location: str, cluster_id: str) -> kubernetes_client.CoreV1Api: """ Fetches a Kubernetes client for the specified GCP project, location, and cluster ID. Args: project_id (str): Google Cloud Project ID location (str): Location of the cluster (e.g., "us-central1-a") cluster_id (str): Name of the Kubernetes cluster Returns: kubernetes_client.CoreV1Api: Kubernetes CoreV1 API client """ # Retrieve cluster information gke_cluster = container_v1.ClusterManagerClient().get_cluster(request={ "name": f"projects/{project_id}/locations/{location}/clusters/{cluster_id}" }) # Obtain Google authentication credentials creds, _ = google.auth.default() auth_req = google.auth.transport.requests.Request() # Refresh the token creds.refresh(auth_req) # Initialize the Kubernetes client configuration object configuration = kubernetes_client.Configuration() # Set the cluster endpoint configuration.host = f'https://{gke_cluster.endpoint}' # Write the cluster CA certificate to a temporary file with NamedTemporaryFile(delete=False) as ca_cert: ca_cert.write(base64.b64decode(gke_cluster.master_auth.cluster_ca_certificate)) configuration.ssl_ca_cert = ca_cert.name # Set the authentication token configuration.api_key_prefix['authorization'] = 'Bearer' configuration.api_key['authorization'] = creds.token # Create and return the Kubernetes CoreV1 API client return kubernetes_client.CoreV1Api(kubernetes_client.ApiClient(configuration)) def main(): project_id = "your-project-id" # Google Cloud Project ID location = "your-cluster-location" # Cluster region (e.g., "us-central1-a") cluster_id = "your-cluster-id" # Cluster name # Retrieve the Kubernetes client core_v1_api = get_k8s_client(project_id, location, cluster_id) # Fetch the kube-system Namespace namespace = core_v1_api.read_namespace(name="kube-system") # Output the Namespace resource in YAML format yaml_output = yaml.dump(namespace.to_dict(), default_flow_style=False) print(yaml_output) if __name__ == "__main__": main()
要注意的是,google-cloud-container 函式庫是為與 GKE 作為服務互動而設計的,而不是直接與 Kubernetes API 互動。例如,雖然您可以使用此程式庫檢索叢集資訊、升級叢集或設定維護策略(類似於使用 gcloud 容器叢集命令執行的操作),但您無法使用它直接取得 Kubernetes API 用戶端。這種差異就是為什麼該函數在從 GKE 獲取必要的叢集詳細資訊後單獨建置 Kubernetes 用戶端。
2. 使用 Google Cloud 進行身份驗證
為了與 GKE 和 Kubernetes API 交互,該函數使用 Google Cloud 的應用程式預設憑證 (ADC) 進行身份驗證。以下是身份驗證過程的每個步驟的工作原理:
google.auth.default()
此函數會擷取程式碼運行環境的 ADC。根據上下文,它可能會返回:
- 使用者帳戶憑證(例如,來自本機開發設定中的 gcloud auth 應用程式預設登入)。
- 服務帳戶憑證(例如,在 Cloud Run 等 Google Cloud 環境中執行時)。
它也會傳回關聯的項目 ID(如果可用),儘管在本例中僅使用憑證。
google.auth.transport.requests.Request()
這將建立一個 HTTP 請求對象,用於處理與驗證相關的網路請求。它在內部使用 Python 的 requests 庫,並提供標準化的方法來刷新憑證或請求存取令牌。
creds.refresh(auth_req)
當使用 google.auth.default() 擷取 ADC 時,憑證物件最初不包含存取權杖(至少在本機環境中)。 fresh() 方法明確取得存取權杖並將其附加到憑證對象,使其能夠對 API 請求進行身份驗證。
以下程式碼示範如何驗證此行為:
gke_cluster = container_v1.ClusterManagerClient().get_cluster(request={ "name": f"projects/{project_id}/locations/{location}/clusters/{cluster_id}" })
範例輸出:
# Obtain Google authentication credentials creds, _ = google.auth.default() auth_req = google.auth.transport.requests.Request() # Inspect credentials before refreshing print(f"Access Token (before refresh()): {creds.token}") print(f"Token Expiry (before refresh()): {creds.expiry}") # Refresh the token creds.refresh(auth_req) # Inspect credentials after refreshing print(f"Access Token (after): {creds.token}") print(f"Token Expiry (after): {creds.expiry}")
在呼叫refresh()之前,token屬性為None。呼叫刷新()後,憑證將填入有效的存取權杖及其到期時間。
3.設定Kubernetes客戶端
Kubernetes 用戶端是使用叢集的 API 端點、CA 憑證的暫存檔案和刷新的承載令牌進行設定的。這確保客戶端可以安全地進行身份驗證並與叢集通訊。
gcloud auth application-default login
CA 憑證暫時儲存並由客戶端引用以進行安全 SSL 通訊。透過這些設置,Kubernetes 用戶端已完全配置並準備好與叢集互動。
範例輸出
這是 kube-system 命名空間的 YAML 輸出範例:
from google.cloud import container_v1 import google.auth import google.auth.transport.requests from kubernetes import client as kubernetes_client from tempfile import NamedTemporaryFile import base64 import yaml def get_k8s_client(project_id: str, location: str, cluster_id: str) -> kubernetes_client.CoreV1Api: """ Fetches a Kubernetes client for the specified GCP project, location, and cluster ID. Args: project_id (str): Google Cloud Project ID location (str): Location of the cluster (e.g., "us-central1-a") cluster_id (str): Name of the Kubernetes cluster Returns: kubernetes_client.CoreV1Api: Kubernetes CoreV1 API client """ # Retrieve cluster information gke_cluster = container_v1.ClusterManagerClient().get_cluster(request={ "name": f"projects/{project_id}/locations/{location}/clusters/{cluster_id}" }) # Obtain Google authentication credentials creds, _ = google.auth.default() auth_req = google.auth.transport.requests.Request() # Refresh the token creds.refresh(auth_req) # Initialize the Kubernetes client configuration object configuration = kubernetes_client.Configuration() # Set the cluster endpoint configuration.host = f'https://{gke_cluster.endpoint}' # Write the cluster CA certificate to a temporary file with NamedTemporaryFile(delete=False) as ca_cert: ca_cert.write(base64.b64decode(gke_cluster.master_auth.cluster_ca_certificate)) configuration.ssl_ca_cert = ca_cert.name # Set the authentication token configuration.api_key_prefix['authorization'] = 'Bearer' configuration.api_key['authorization'] = creds.token # Create and return the Kubernetes CoreV1 API client return kubernetes_client.CoreV1Api(kubernetes_client.ApiClient(configuration)) def main(): project_id = "your-project-id" # Google Cloud Project ID location = "your-cluster-location" # Cluster region (e.g., "us-central1-a") cluster_id = "your-cluster-id" # Cluster name # Retrieve the Kubernetes client core_v1_api = get_k8s_client(project_id, location, cluster_id) # Fetch the kube-system Namespace namespace = core_v1_api.read_namespace(name="kube-system") # Output the Namespace resource in YAML format yaml_output = yaml.dump(namespace.to_dict(), default_flow_style=False) print(yaml_output) if __name__ == "__main__": main()
結論
這種方法強調了使用相同程式碼與 Kubernetes API 互動的可移植性,無論是在本地運行還是在 Cloud Run 等 Google Cloud 服務上運行。透過利用應用程式預設憑證 (ADC),我們示範了一種靈活的方法來動態產生 Kubernetes API 用戶端,而無需依賴預先產生的設定檔或外部工具。這使得建立能夠無縫適應不同環境的應用程式變得容易,從而簡化了開發和部署工作流程。
以上是使用 Python 為 Google Kubernetes Engine (GKE) 建置 Kubernetes 用戶端的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。
