gabrielpasv
gabrielpasv

Reputation: 21

python app to call kubernetes to create pod programmatically

I am designing a web application where users can have trade bots running. So they will sign in, pay for membership then they will create a bot, enter the credentials and start the bot. The user can stop / start the trade bot.

I am trying to do this using kubernetes, so I will have everything running on kubernetes. I will create a namespace named bots and all bots for all clients will be running inside this bot namespace.

Stack is : python (django framework ) + mysql + aws + kubernetes

question: Is there a way to programmatically create a pod using python ? I want to integrate with the application code. So when user clicks on create new bot it will start a new pod running with all the parameters for the specific user.

Basically each pod will be a tenant. But a tenant can have multiple pods / bots. So how do that ? Is there any kubernetes python lib that does it ? I did some online search but didn't find anything. Thanks

Upvotes: 1

Views: 9031

Answers (2)

tdimitch
tdimitch

Reputation: 51

As noted by Harsh Manvar, you can user the official Kubernetes Python client. Here is a short function which allows to do it.

from kubernetes import client, config, utils
from kubernetes.client.api import core_v1_api

config.load_incluster_config()
try:
    c = Configuration().get_default_copy()
except AttributeError:
    c = Configuration()
    c.assert_hostname = False
Configuration.set_default(c)
self.core_v1 = core_v1_api.CoreV1Api()

def open_pod(self, cmd: list, 
                   pod_name: str, 
                   namespace: str='bots', 
                   image: str=f'{repository}:{tag}', 
                   restartPolicy: str='Never', 
                   serviceAccountName: str='bots-service-account'):
    '''
    This method launches a pod in kubernetes cluster according to command
    '''
    
    api_response = None
    try:
        api_response = self.core_v1.read_namespaced_pod(name=pod_name,
                                                        namespace=namespace)
    except ApiException as e:
        if e.status != 404:
            print("Unknown error: %s" % e)
            exit(1)

    if not api_response:
        print(f'From {os.path.basename(__file__)}: Pod {pod_name} does not exist. Creating it...')
        # Create pod manifest
        pod_manifest = {
            'apiVersion': 'v1',
            'kind': 'Pod',
            'metadata': {
                'labels': {
                    'bot': current-bot
                },
                'name': pod_name
            },
            'spec': {
                'containers': [{
                    'image': image,
                    'pod-running-timeout': '5m0s',
                    'name': f'container',
                    'args': cmd,
                    'env': [
                        {'name': 'env_variable', 'value': env_value},
                    ]
                }],
                # 'imagePullSecrets': client.V1LocalObjectReference(name='regcred'), # together with a service-account, allows to access private repository docker image
                'restartPolicy': restartPolicy,
                'serviceAccountName': bots-service-account
            }
        }
        
        print(f'POD MANIFEST:\n{pod_manifest}')

        api_response = self.core_v1.create_namespaced_pod(body=pod_manifest,                                                          namespace=namespace)

        while True:
            api_response = self.core_v1.read_namespaced_pod(name=pod_name,
                                                            namespace=namespace)
            if api_response.status.phase != 'Pending':
                break
            time.sleep(0.01)
        
        print(f'From {os.path.basename(__file__)}: Pod {pod_name} in {namespace} created.')
        return pod_name

For further investigation, refer to the examples in the official github repo: https://github.com/kubernetes-client/python/tree/master/examples

Upvotes: 4

Harsh Manvar
Harsh Manvar

Reputation: 30160

you can use the official Python Kubernetes client to create and manage the POD across the cluster programmatically.

https://github.com/kubernetes-client/python

You can keep one YAML file and replace the values into as per requirement like Deployment Name, Ports and apply the files to the cluster it will create the POD with base image.

Upvotes: 1

Related Questions