<p>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.</p>
<p>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.</p>
<p>Stack is :   python (django framework ) + mysql + aws + kubernetes</p>
<p>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.</p>
<p>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</p>

gabrielpasv
<p>As noted by Harsh Manvar, you can user the official Kubernetes Python client. Here is a short function which allows to do it.</p>
<pre><code>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(&quot;Unknown error: %s&quot; % 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
</code></pre>
<p>For further investigation, refer to the examples in the official github repo: <a href="https://github.com/kubernetes-client/python/tree/master/examples" rel="nofollow noreferrer">https://github.com/kubernetes-client/python/tree/master/examples</a></p>
