이 블로그 게시물에서는 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 라이브러리는 Kubernetes API와 직접적으로 상호작용하는 것이 아니라 GKE as a Service와 상호작용하도록 설계되었다는 점에 유의하는 것이 중요합니다. 예를 들어 이 라이브러리를 사용하여 클러스터 정보를 검색하거나, 클러스터를 업그레이드하거나, 유지 관리 정책을 구성할 수 있지만(gcloud Container Clusters 명령어로 수행할 수 있는 작업과 유사), Kubernetes API 클라이언트를 직접 가져오는 데 사용할 수는 없습니다. 이러한 차이로 인해 함수는 GKE에서 필요한 클러스터 세부정보를 가져온 후 Kubernetes 클라이언트를 별도로 구성합니다.
2. Google Cloud로 인증
GKE 및 Kubernetes API와 상호작용하기 위해 이 함수는 Google Cloud의 애플리케이션 기본 사용자 인증 정보(ADC)를 사용하여 인증합니다. 인증 프로세스의 각 단계는 다음과 같습니다.
google.auth.default()
이 함수는 코드가 실행되는 환경에 대한 ADC를 검색합니다. 상황에 따라 다음이 반환될 수 있습니다.
- 사용자 계정 자격 증명(예: 로컬 개발 설정의 gcloud 인증 애플리케이션 기본 로그인에서)
- 서비스 계정 자격 증명(예: Cloud Run과 같은 Google Cloud 환경에서 실행하는 경우)
사용 가능한 경우 관련 프로젝트 ID도 반환하지만, 이 경우에는 자격 증명만 사용됩니다.
google.auth.transport.requests.Request()
인증 관련 네트워크 요청을 처리하기 위한 HTTP 요청 개체를 생성합니다. 내부적으로 Python의 요청 라이브러리를 사용하고 자격 증명을 새로 고치거나 액세스 토큰을 요청하는 표준화된 방법을 제공합니다.
creds.refresh(auth_req)
google.auth.default()를 사용하여 ADC를 검색할 때 자격 증명 객체는 처음에 액세스 토큰을 포함하지 않습니다(적어도 로컬 환경에서는). Refresh() 메소드는 명시적으로 액세스 토큰을 획득하고 이를 자격 증명 객체에 연결하여 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()를 호출하기 전에는 토큰 속성이 None입니다. 새로 고침()이 호출된 후 자격 증명은 유효한 액세스 토큰과 만료 시간으로 채워집니다.
3. 쿠버네티스 클라이언트 구성
Kubernetes 클라이언트는 클러스터의 API 엔드포인트, CA 인증서용 임시 파일, 새로 고친 Bearer 토큰을 사용하여 구성됩니다. 이렇게 하면 클라이언트가 안전하게 인증하고 클러스터와 통신할 수 있습니다.
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()
결론
이 접근 방식은 로컬에서 실행하든 Cloud Run과 같은 Google Cloud 서비스에서 실행하든 동일한 코드를 사용하여 Kubernetes API와 상호작용하는 이식성을 강조합니다. ADC(애플리케이션 기본 자격 증명)를 활용하여 사전 생성된 구성 파일이나 외부 도구에 의존하지 않고 Kubernetes API 클라이언트를 동적으로 생성하는 유연한 방법을 시연했습니다. 이를 통해 다양한 환경에 원활하게 적응할 수 있는 애플리케이션을 쉽게 구축하고 개발 및 배포 워크플로를 단순화할 수 있습니다.
위 내용은 Python으로 Google Kubernetes Engine(GKE)용 Kubernetes 클라이언트 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python은 엄격하게 라인 별 실행이 아니지만 통역사 메커니즘을 기반으로 최적화되고 조건부 실행입니다. 통역사는 코드를 PVM에 의해 실행 된 바이트 코드로 변환하며 상수 표현식을 사전 컴파일하거나 루프를 최적화 할 수 있습니다. 이러한 메커니즘을 이해하면 코드를 최적화하고 효율성을 향상시키는 데 도움이됩니다.

Python에는 두 개의 목록을 연결하는 방법이 많이 있습니다. 1. 연산자 사용 간단하지만 큰 목록에서는 비효율적입니다. 2. 효율적이지만 원래 목록을 수정하는 확장 방법을 사용하십시오. 3. 효율적이고 읽기 쉬운 = 연산자를 사용하십시오. 4. 메모리 효율적이지만 추가 가져 오기가 필요한 itertools.chain function을 사용하십시오. 5. 우아하지만 너무 복잡 할 수있는 목록 구문 분석을 사용하십시오. 선택 방법은 코드 컨텍스트 및 요구 사항을 기반으로해야합니다.

Python 목록을 병합하는 방법에는 여러 가지가 있습니다. 1. 단순하지만 큰 목록에 대한 메모리 효율적이지 않은 연산자 사용; 2. 효율적이지만 원래 목록을 수정하는 확장 방법을 사용하십시오. 3. 큰 데이터 세트에 적합한 itertools.chain을 사용하십시오. 4. 사용 * 운영자, 한 줄의 코드로 중소형 목록을 병합하십시오. 5. Numpy.concatenate를 사용하십시오. 이는 고성능 요구 사항이있는 대규모 데이터 세트 및 시나리오에 적합합니다. 6. 작은 목록에 적합하지만 비효율적 인 Append Method를 사용하십시오. 메소드를 선택할 때는 목록 크기 및 응용 프로그램 시나리오를 고려해야합니다.

CompiledLanguagesOfferSpeedSecurity, while InterpretedLanguagesProvideeaseofusEandportability

Python에서, for 루프는 반복 가능한 물체를 가로 지르는 데 사용되며, 조건이 충족 될 때 반복적으로 작업을 수행하는 데 사용됩니다. 1) 루프 예제 : 목록을 가로 지르고 요소를 인쇄하십시오. 2) 루프 예제 : 올바르게 추측 할 때까지 숫자 게임을 추측하십시오. 마스터 링 사이클 원리 및 최적화 기술은 코드 효율성과 안정성을 향상시킬 수 있습니다.

목록을 문자열로 연결하려면 Python의 join () 메소드를 사용하는 것이 최선의 선택입니다. 1) join () 메소드를 사용하여 목록 요소를 ''.join (my_list)과 같은 문자열로 연결하십시오. 2) 숫자가 포함 된 목록의 경우 연결하기 전에 맵 (str, 숫자)을 문자열로 변환하십시오. 3) ','. join (f '({fruit})'forfruitinfruits와 같은 복잡한 형식에 발전기 표현식을 사용할 수 있습니다. 4) 혼합 데이터 유형을 처리 할 때 MAP (str, mixed_list)를 사용하여 모든 요소를 문자열로 변환 할 수 있도록하십시오. 5) 큰 목록의 경우 ''.join (large_li

PythonuseSahybrideactroach, combingingcompytobytecodeandingretation.1) codeiscompiledToplatform-IndependentBecode.2) bytecodeistredbythepythonvirtonmachine, enterancingefficiency andportability.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구