How can I read a Jupyter notebook token from the k8s Python API?

11/25/2021

I am creating a k8s deployment, service, and ingress using the k8s Python API. The deployment uses the minimal-notebook container to create a Jupyter notebook instance.

After creating the deployment, how can I read the token for my minimal-notebook pod using the k8s Python API?

-- ktm5124
jupyter
jupyter-notebook
kubernetes
python

1 Answer

11/25/2021

You would need to get the pod logs, and extract the token. Given that the pod is already running

k get pods
NAME       READY   STATUS    RESTARTS   AGE
mininote   1/1     Running   0          17m
k get pod mininote -o json | jq '.spec.containers[].image'
"jupyter/minimal-notebook"

you could do this: my pod's name is mininote and it is running in the default namespace

import re
from kubernetes.client.rest import ApiException
from kubernetes import client, config

config.load_kube_config()
pod_name = "mininote"
namespace_name = "default"

try:
    api = client.CoreV1Api()
    response = api.read_namespaced_pod_log(name=pod_name, namespace=namespace_name)
    match = re.search(r'token=([0-9a-z]*)', response)
    print(match.group(1))
except ApiException as e:
    print('Found exception in reading the logs:')
    print(e)

running:

> python main.py
174c891b5db325b2aec283df90525c68ab02b02e3a565da5
-- jabbson
Source: StackOverflow