[Kubernetes](EN) Make pod from yaml file using Kubernetes Python client
Make pod from yaml file using Kubernetes Python client
Environment and Prerequisite
- Kubernetes
- Assume default setting is set in
~/.kube/config file
Usage
Example YAML File
- File name is
nginx_deployment.yaml
in this post.
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
Code
- Assume default setting is set in
~/.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}")
Execution Results
$ 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