[Kubernetes] Kubernetes Python 클라이언트를 사용해 yaml 파일로부터 pod 생성하기

Kubernetes Python 클라이언트를 사용해 yaml 파일로부터 pod를 생성해보자


환경

  • Kubernetes
  • 기본 설정들이 ~/.kube/config file에 되어있다고 가정


사용법

예시 YAML 파일

  • 이 글에서 파일명은 nginx_deployment.yaml다.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2 # tells deployment to run 2 pods matching the template
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

코드

  • 기본 설정들이 ~/.kube/config file에 되어있다고 가정
import time
from kubernetes import client as kubernetes_client
from kubernetes import utils
from kubernetes import config
import yaml


# read yaml file as object
with open("nginx_deployment.yaml") as f:
    nginx_deployment_yaml = yaml.safe_load(f)

# load default config
# assume that default setting is set in ~/.kube/config
config.load_kube_config()

# load kubernetes client
k8s_client = kubernetes_client.api_client.ApiClient()

# create pods from yaml object
utils.create_from_yaml(k8s_client, yaml_objects=[
                       nginx_deployment_yaml], namespace="default")

# wait for pods
time.sleep(3)

# list pods
core_v1_api = kubernetes_client.CoreV1Api()
pods = core_v1_api.list_namespaced_pod("default")
for pod in pods.items:
    print(f"{pod.metadata.name} {pod.status.phase} {pod.status.pod_ip} {pod.metadata.namespace}")

실행 결과

$ python test.py
nginx-deployment-7fb96c846b-bgvkv Running 172.17.0.3 default
nginx-deployment-7fb96c846b-g9l6l Running 172.17.0.4 default
$ kubectl get pods -n default
NAME                                READY   STATUS    RESTARTS   AGE
nginx-deployment-7fb96c846b-bgvkv   1/1     Running   0          20s
nginx-deployment-7fb96c846b-g9l6l   1/1     Running   0          20s


참고자료