From f68380a461b155586b5922e904e3123d45c09742 Mon Sep 17 00:00:00 2001
From: Maarten de Waard <maarten@greenhost.nl>
Date: Thu, 29 Sep 2022 16:38:29 +0200
Subject: [PATCH] Add an environment variable that defines which config to load

See https://stackoverflow.com/a/63873828
---
 config.py             | 5 +++++
 docker-compose.yml    | 3 +++
 helpers/kubernetes.py | 7 ++++++-
 3 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/config.py b/config.py
index efab954f..2cb00177 100644
--- a/config.py
+++ b/config.py
@@ -15,3 +15,8 @@ KRATOS_PUBLIC_URL = str(os.environ.get("KRATOS_PUBLIC_URL")) + "/"
 
 SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
 SQLALCHEMY_TRACK_MODIFICATIONS = False
+
+# Set this to "true" to load the config from a Kubernetes serviceaccount
+# running in a Kubernetes pod. Set it to "false" to load the config from the
+# `KUBECONFIG` environment variable.
+LOAD_INCLUSTER_CONFIG = os.environ.get("LOAD_INCLUSTER_CONFIG").lower() == "true"
diff --git a/docker-compose.yml b/docker-compose.yml
index e261b485..4eacc2b9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -32,6 +32,9 @@ services:
       - SECRET_KEY=$FLASK_SECRET_KEY
       - HYDRA_CLIENT_SECRET=$HYDRA_CLIENT_SECRET
       - KUBECONFIG=/.kube/config
+
+      # Disable loading config from the service account
+      - LOAD_INCLUSTER_CONFIG=false
     ports:
       - "5000:5000"
     user: "${KUBECTL_UID}:${KUBECTL_GID}"
diff --git a/helpers/kubernetes.py b/helpers/kubernetes.py
index 280cceaf..202d53cc 100644
--- a/helpers/kubernetes.py
+++ b/helpers/kubernetes.py
@@ -14,12 +14,17 @@ from kubernetes.utils import create_from_yaml
 from kubernetes.utils.create_from_yaml import FailToCreateError
 from flask import current_app
 
+from config import LOAD_INCLUSTER_CONFIG
+
 # Load the kube config once
 #
 # By default this loads whatever we define in the `KUBECONFIG` env variable,
 # otherwise loads the config from default locations, similar to what kubectl
 # does.
-config.load_kube_config()
+if LOAD_INCLUSTER_CONFIG:
+    config.load_incluster_config()
+else:
+    config.load_kube_config()
 
 def create_variables_secret(app_slug, variables_filepath):
     """Checks if a variables secret for app_name already exists, generates it if necessary.
-- 
GitLab