Felix
Felix

Reputation: 3591

How can a Python app find out that it's running inside a Kubernetes pod?

I have a Python script that should have slightly different behaviour if it's running inside a Kubernetes pod.

But how can I find out that whether I'm running inside Kubernetes -- or not?

Upvotes: 0

Views: 1092

Answers (2)

Ifra Ibrahim
Ifra Ibrahim

Reputation: 34

You can create and set an environment variable to some value when deploying your script to the cluster, then in your script you just check if the environment variable is present and set.

THE ENV FILE DEPLOYED TO CLUSTER:

KUBERNETES_POD=TRUE

SCRIPT:

import os

load_dotenv()
is_kube = os.getenv('KUBERNETES_POD',default=False)

if is_kube:
    print('in cluster')

Then just make sure you do not have the environment variable set locally so that the is_kube boolean defaults to False.

If you are running a Django application, you can get the host name from the request parameter passed to each view with the get_host method:

def function_view(request):
    host = request.get_host()
        if host == 'your-cluster_ip.com'
            print('in cluster')

Upvotes: 0

Blender Fox
Blender Fox

Reputation: 5625

An easy way I use (and it's not Python specific), is to check whether kubernetes.default.svc.cluster.local resolves to an IP (you don't need to try to access, just see if it resolves successfully)

If it does, the script/program is running inside a cluster. If it doesn't, proceed on the assumption it's not running inside a cluster.

Upvotes: 5

Related Questions