搜尋
首頁後端開發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的執行模型:編譯,解釋還是兩者?Python的執行模型:編譯,解釋還是兩者?May 10, 2025 am 12:04 AM

pythonisbothCompileDIntered。

Python是按線執行的嗎?Python是按線執行的嗎?May 10, 2025 am 12:03 AM

Python不是嚴格的逐行執行,而是基於解釋器的機制進行優化和條件執行。解釋器將代碼轉換為字節碼,由PVM執行,可能會預編譯常量表達式或優化循環。理解這些機制有助於優化代碼和提高效率。

python中兩個列表的串聯替代方案是什麼?python中兩個列表的串聯替代方案是什麼?May 09, 2025 am 12:16 AM

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

Python:合併兩個列表的有效方法Python:合併兩個列表的有效方法May 09, 2025 am 12:15 AM

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

編譯的與解釋的語言:優點和缺點編譯的與解釋的語言:優點和缺點May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python:對於循環,最完整的指南Python:對於循環,最完整的指南May 09, 2025 am 12:05 AM

Python中,for循環用於遍歷可迭代對象,while循環用於條件滿足時重複執行操作。 1)for循環示例:遍歷列表並打印元素。 2)while循環示例:猜數字遊戲,直到猜對為止。掌握循環原理和優化技巧可提高代碼效率和可靠性。

python concatenate列表到一個字符串中python concatenate列表到一個字符串中May 09, 2025 am 12:02 AM

要將列表連接成字符串,Python中使用join()方法是最佳選擇。 1)使用join()方法將列表元素連接成字符串,如''.join(my_list)。 2)對於包含數字的列表,先用map(str,numbers)轉換為字符串再連接。 3)可以使用生成器表達式進行複雜格式化,如','.join(f'({fruit})'forfruitinfruits)。 4)處理混合數據類型時,使用map(str,mixed_list)確保所有元素可轉換為字符串。 5)對於大型列表,使用''.join(large_li

Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

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脫衣器

Video Face Swap

Video Face Swap

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

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

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