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?
CodePudding user response:
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.
CodePudding user response:
you can create and set an environment variable to some value when deploying your script to the cluster ,,then on your script you just check if the env value is present.
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 env 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 paramater passed to each view
def function_view(request):
host = request.get_host()
if host == 'your-cluster_ip.com'
print('in cluster')