搜尋
首頁後端開發Python教學使用 Python 為 Google Kubernetes Engine (GKE) 建置 Kubernetes 用戶端

Building a Kubernetes Client for Google Kubernetes Engine (GKE) in Python

這篇部落格文章介紹了一種使用 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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用Python查找文本文件的ZIPF分佈如何使用Python查找文本文件的ZIPF分佈Mar 05, 2025 am 09:58 AM

本教程演示如何使用Python處理Zipf定律這一統計概念,並展示Python在處理該定律時讀取和排序大型文本文件的效率。 您可能想知道Zipf分佈這個術語是什麼意思。要理解這個術語,我們首先需要定義Zipf定律。別擔心,我會盡量簡化說明。 Zipf定律 Zipf定律簡單來說就是:在一個大型自然語言語料庫中,最頻繁出現的詞的出現頻率大約是第二頻繁詞的兩倍,是第三頻繁詞的三倍,是第四頻繁詞的四倍,以此類推。 讓我們來看一個例子。如果您查看美國英語的Brown語料庫,您會注意到最頻繁出現的詞是“th

如何在Python中下載文件如何在Python中下載文件Mar 01, 2025 am 10:03 AM

Python 提供多種從互聯網下載文件的方法,可以使用 urllib 包或 requests 庫通過 HTTP 進行下載。本教程將介紹如何使用這些庫通過 Python 從 URL 下載文件。 requests 庫 requests 是 Python 中最流行的庫之一。它允許發送 HTTP/1.1 請求,無需手動將查詢字符串添加到 URL 或對 POST 數據進行表單編碼。 requests 庫可以執行許多功能,包括: 添加表單數據 添加多部分文件 訪問 Python 的響應數據 發出請求 首

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

python中的圖像過濾python中的圖像過濾Mar 03, 2025 am 09:44 AM

處理嘈雜的圖像是一個常見的問題,尤其是手機或低分辨率攝像頭照片。 本教程使用OpenCV探索Python中的圖像過濾技術來解決此問題。 圖像過濾:功能強大的工具圖像過濾器

如何使用Python使用PDF文檔如何使用Python使用PDF文檔Mar 02, 2025 am 09:54 AM

PDF 文件因其跨平台兼容性而廣受歡迎,內容和佈局在不同操作系統、閱讀設備和軟件上保持一致。然而,與 Python 處理純文本文件不同,PDF 文件是二進製文件,結構更複雜,包含字體、顏色和圖像等元素。 幸運的是,借助 Python 的外部模塊,處理 PDF 文件並非難事。本文將使用 PyPDF2 模塊演示如何打開 PDF 文件、打印頁面和提取文本。關於 PDF 文件的創建和編輯,請參考我的另一篇教程。 準備工作 核心在於使用外部模塊 PyPDF2。首先,使用 pip 安裝它: pip 是 P

如何在django應用程序中使用redis緩存如何在django應用程序中使用redis緩存Mar 02, 2025 am 10:10 AM

本教程演示瞭如何利用Redis緩存以提高Python應用程序的性能,特別是在Django框架內。 我們將介紹REDIS安裝,Django配置和性能比較,以突出顯示BENE

引入自然語言工具包(NLTK)引入自然語言工具包(NLTK)Mar 01, 2025 am 10:05 AM

自然語言處理(NLP)是人類語言的自動或半自動處理。 NLP與語言學密切相關,並與認知科學,心理學,生理學和數學的研究有聯繫。在計算機科學

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

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

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中