How to create a kubernetes pod from python code

Introduction

To make a pod with kubernetes, you can first create a yaml file of the pod and then apply the created yaml file with a command, but I want to create a pod from python code without using a command. When I looked it up, I couldn't find the article, and I had a hard time writing the program, so I'll share it.

environment

Basic method of creating a pod

First, try to create a basic pod. Any yaml file to create a pod is fine, but for the time being, create a simple pod.yaml file.

$ vim pod.yaml

It's easy to copy and paste with: set paste

pod.yaml


#Rules for writing pods
apiVersion: v1
kind: Pod
#Detailed information such as pod name and label
metadata:
  name: myapp-pod  #Give the pod a name
  labels:
    app: myapp  #Label app->Add myapp
#Information of the container body to be placed in the pod
spec:
  containers:
    - name: demo-container  #Give the container a name
      image: nginx  #Container name(Matches the name of Docker Hub)
      ports:
        - containerPort: 80  #Use port 80

Apply pod.yaml to create a pod.

$ kubectl apply -f pod.yaml
pod/myapp-pod created

Check if the pod is made.

$ kubectl get pod
NAME        READY   STATUS    RESTARTS   AGE
myapp-pod   1/1     Running   0          34s

The pod I made is used up, so delete it.

$ kubectl delete -f pod.yaml
pod "myapp-pod" deleted
$ kubectl get pod
No resources found in c0118272 namespace.

Created from python

Install what you need.

$ pip3 install flask
$ pip3 install kubernetes

Create a python program that creates a pod with the name podcreate.py in the same directory as pod.yaml. Change namespace to your own namespace name. The basic is default.

$ vim podcreate.py

podcreate.py


from flask import Flask
from flask import request
from kubernetes import client, config, watch
import yaml

app = Flask(__name__)
@app.route('/')
def pod_create():
    config.load_kube_config()
    with open("pod.yaml", "r") as f:
        pod = yaml.safe_load(f)
        k8s_apps_v1 = client.CoreV1Api()
        resp = k8s_apps_v1.create_namespaced_pod(body=pod, namespace="c0118272")
        print("pod created. status='%s'" % resp.metadata.name)
    return "pod created. status='%s'" % resp.metadata.name

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

Check the positional relationship of the files.

$ ls
podcreate.py  pod.yaml

Since I wrote it in flask, I will display it on the browser and execute it.

$ export FLASK_APP=podcreate.py
$ flask run --host=0.0.0.0
 * Serving Flask app "podcreate.py"
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * 

Try running it in your browser. If the url is local, it is http://0.0.0.0:5000. If it is not local, the port is 5000 and the IP address is different for each execution environment. 1-1.PNG

If it looks like the image above, you're successful!

Check with the command.

$ kubectl get pod
NAME        READY   STATUS    RESTARTS   AGE
myapp-pod   1/1     Running   0          3m11s

Once you have a pod, you're done! !!

in conclusion

I'm using the kubernetes api, but it's difficult and I'm not sure, so please check each application method! Have a good research life ~

Recommended Posts

How to create a kubernetes pod from python code
How to create a clone from Github
How to create a Python virtual environment (venv)
How to open a web browser from python
How to create a function object from a string
How to create a JSON file in Python
How to generate a Python object from JSON
How to make a Python package using VS Code
Python script to create a JSON file from a CSV file
[Python] How to create a 2D histogram with Matplotlib
[Python] How to call a c function from python (ctypes)
How to write a Python class
Create folders from '01' to '12' with python
How to create a Conda package
How to create a virtual bridge
How to create a Dockerfile (basic)
Create a Kubernetes Operator in Python
How to access wikipedia from python
5 Ways to Create a Python Chatbot
How to create a config file
How to slice a block multiple array from a multiple array in Python
How to run a Python program from within a shell script
How to launch AWS Batch from a python client app
[Python Kivy] How to create a simple pop up window
How to create a radial profile from astronomical images (Chandra, XMM etc.) using python
How to use NUITKA-Utilities hinted-compilation to easily create an executable file from a Python script
I wrote Python code to create a table (view) dependency diagram (PlantUML) from SQL
How to create a git clone folder
Qiita (1) How to write a code name
[Python] How to make a class iterable
[Python] How to convert a 2D list to a 1D list
How to update Google Sheets from Python
Send a message from Python to Slack
How to create an instance of a particular class from dict using __new__ () in python
How to get a string from a command line argument in python
[Python] How to get & change rows / columns / values from a table.
[Python] How to invert a character string
How to get a stacktrace in python
Simple code to call a python program from Javascript on EC2
How to connect to Cloud Firestore from Google Cloud Functions with python code
How to access RDS from Lambda (python)
Create a deb file from a python package
[Python] How to create a table from list (basic operation of table creation / change of matrix name)
How to remove duplicates from a Python list while preserving order.
How to run a Maya Python script
Create a tool to automatically furigana with html using Mecab from Python3
Steps to create a Python virtual environment with VS Code on Windows
How to get a value from a parameter store in lambda (using python)
3. Natural language processing with Python 1-2. How to create a corpus: Aozora Bunko
Send a message from Slack to a Python server
[Python] List Comprehension Various ways to create a list
How to read a CSV file with Python 2/3
How to code a drone using image recognition
How to clear tuples in a list (Python)
How to embed a variable in a python string
Study from Python Hour7: How to use classes
I want to create a window in Python
Create a New Todoist Task from Python Script
[Python] How to read data from CIFAR-10 and CIFAR-100
[python] Create table from pandas DataFrame to postgres
How to add a Python module search path