본문 바로가기

공부기록/MLOps | Infra

[k8s] python sdk를 이용해 Pod 내에서 Kubernetes API 사용하기

반응형

방법1. config file 사용

config.load_incluster_config()

v1 = client.CoreV1Api()

pod내부가 아닌 경우엔 load_kube_config() 를 사용하지만 pod내부에서 config file을 로드할 때는 load_incluster_config() 를 사용한다.

 

 

방법 1을 사용해도 권한이 없어서 403 errors 가 발생할 수 있다. 이런 경우에 클러스터롤바인딩이 필요하다.

관련 내용은 kubernetes-client github에서 확인할 수 있다.

더보기

Shows how to load a Kubernetes config from within a cluster. This scriptmust be run within a pod. You can start a pod with a Python image (forexample, `python:latest`), exec into the pod, install the library, then runthis example.If you get 403 errors from the API server you will have to configure RBAC toadd permission to list pods by applying the following manifest:

 

clusterrolebinding

serviceaccount에 cluster-adim 클러스터롤을 바인딩하였다.

 

kubectl create clusterrolebinding <클러스터롤바인딩명>
   --clusterrole=cluster-admin
      --serviceaccount=<서비스어카운트명>

 

 

방법2. pod 내부에 저장된 인증 정보 사용

pod 내부에서 Kubernetes API에 접근하고자 할 때 사용할 수 있는 파일과 정보들은 아래와 같다.

  • API 서버: https://kubernetes.default
  • token 위치 : /var/run/secrets/kubernetes.io/serviceaccount/token
  • cert 위치: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
from kubernetes import client, config

config = client.Configuration()

config.api_key['authorization'] = open('/var/run/secrets/kubernetes.io/serviceaccount/token').read()
config.api_key_prefix['authorization'] = 'Bearer'
config.host = 'https://kubernetes.default'
config.ssl_ca_cert = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'
config.verify_ssl=True

 

참고

반응형

'공부기록 > MLOps | Infra' 카테고리의 다른 글

[kubeflow] kfp.dsl을 사용한 pod scheduling  (0) 2022.09.02
[k8s] Backup and Restore Methods  (0) 2022.08.29
[k8s] Cluster Upgrade Process  (0) 2022.08.29
[k8s] drain and cordon  (0) 2022.08.28
[k8s] Multi Container PODs  (0) 2022.08.28