Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Created February 10, 2019 14:08
Show Gist options
  • Save sangheestyle/1baa2301ff163b3fced8fda285528b7f to your computer and use it in GitHub Desktop.
Save sangheestyle/1baa2301ff163b3fced8fda285528b7f to your computer and use it in GitHub Desktop.
Create and delete pods on kubernetes via Python kubernetes API
"""
Intuition:
Assume we have pod1 and pod2 in 'default' namespace, and
we want to create and delete pod1 or pod2 on the fly.
Also, we can monitor their status on the fly.
Extention:
If our intuition works on kubernates python API, then
we can easily manage our pods to allocate arbitrary
tasks.
Reference:
a. Requirements: https://goo.gl/JXyxCd
b. Basic: https://github.com/kubernetes-client/python/blob/master/examples/notebooks/create_pod.ipynb
c. Minikube for your local: https://github.com/kubernetes/minikube
"""
from kubernetes import client, config
def show_pod_status(namespace):
ret = v1.list_namespaced_pod(namespace)
for i in ret.items:
vals = (i.status.pod_ip, i.metadata.namespace, i.metadata.name)
print("%s %s %s" % vals)
# Load config
config.load_kube_config()
v1 = client.CoreV1Api()
# Define container
container = client.V1Container(
name="busybox",
image="busybox",
args=["sleep", "3600"])
# Define Pod based on containers
pod1 = client.V1Pod()
spec = client.V1PodSpec(containers=[container])
pod1.metadata = client.V1ObjectMeta(name="pod1")
pod1.spec = spec
pod2 = client.V1Pod()
spec = client.V1PodSpec(containers=[container])
pod2.metadata = client.V1ObjectMeta(name="pod2")
pod2.spec = spec
# Show current status
print("=== Before creation: ")
show_pod_status("default")
# Create pod
v1.create_namespaced_pod(namespace="default",body=pod1)
v1.create_namespaced_pod(namespace="default",body=pod2)
# Show current status
print("=== After creation: ")
show_pod_status("default")
# Delete pod2 only
v1.delete_namespaced_pod(name=pod2.metadata.name, namespace="default", body=client.V1DeleteOptions())
# After a couple of sec (kubernetes tries to delete pod)
# You can see only pod1
print("=== After deletion: ")
show_pod_status("default")
@sangheestyle
Copy link
Author

Wondering:

  • auto-healing?
  • who actually controll?
  • where the state saved?

@sangheestyle
Copy link
Author

I used virtualbox backend for minikube:

$ brew cask install virtualbox

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment