From 9339d82c5379d35c7ab17924627bda5b3fe7473c Mon Sep 17 00:00:00 2001 From: Erik Sundell Date: Tue, 1 Sep 2020 16:12:16 +0200 Subject: [PATCH] Support EnvVar's with 'valueFrom' as well as with 'value' --- kubespawner/objects.py | 14 ++++++++++++- tests/test_objects.py | 46 +++++++++++++++++++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/kubespawner/objects.py b/kubespawner/objects.py index 257fffd7..f1041df6 100644 --- a/kubespawner/objects.py +++ b/kubespawner/objects.py @@ -274,12 +274,24 @@ def make_pod( if all([e is None for e in container_security_context.to_dict().values()]): container_security_context = None + # Transform a dict into valid Kubernetes EnvVar Python representations. This + # representation shall always have a "name" field as well as either a + # "value" field or "value_from" field. For examples see the + # test_make_pod_with_env function. + prepared_env = [] + for k, v in (env or {}).items(): + if type(v) == dict: + if not "name" in v: + v["name"] = k + prepared_env.append(get_k8s_model(V1EnvVar, v)) + else: + prepared_env.append(V1EnvVar(name=k, value=v)) notebook_container = V1Container( name='notebook', image=image, working_dir=working_dir, ports=[V1ContainerPort(name='notebook-port', container_port=port)], - env=[V1EnvVar(k, v) for k, v in (env or {}).items()], + env=prepared_env, args=cmd, image_pull_policy=image_pull_policy, lifecycle=lifecycle_hooks, diff --git a/tests/test_objects.py b/tests/test_objects.py index 1178fd2f..a537cce9 100644 --- a/tests/test_objects.py +++ b/tests/test_objects.py @@ -443,13 +443,30 @@ def test_make_pod_resources_all(): def test_make_pod_with_env(): """ - Test specification of a pod with custom environment variables + Test specification of a pod with custom environment variables. """ assert api_client.sanitize_for_serialization(make_pod( name='test', image='jupyter/singleuser:latest', env={ - 'TEST_KEY': 'TEST_VALUE' + 'TEST_KEY_1': 'TEST_VALUE', + 'TEST_KEY_2': { + 'valueFrom': { + 'secretKeyRef': { + 'name': 'my-k8s-secret', + 'key': 'password', + }, + }, + }, + 'TEST_KEY_NAME_IGNORED': { + 'name': 'TEST_KEY_3', + 'valueFrom': { + 'secretKeyRef': { + 'name': 'my-k8s-secret', + 'key': 'password', + }, + }, + }, }, cmd=['jupyterhub-singleuser'], port=8888, @@ -464,7 +481,30 @@ def test_make_pod_with_env(): 'automountServiceAccountToken': False, "containers": [ { - "env": [{'name': 'TEST_KEY', 'value': 'TEST_VALUE'}], + "env": [ + { + 'name': 'TEST_KEY_1', + 'value': 'TEST_VALUE', + }, + { + 'name': 'TEST_KEY_2', + 'valueFrom': { + 'secretKeyRef': { + 'name': 'my-k8s-secret', + 'key': 'password', + }, + }, + }, + { + 'name': 'TEST_KEY_3', + 'valueFrom': { + 'secretKeyRef': { + 'name': 'my-k8s-secret', + 'key': 'password', + }, + }, + }, + ], "name": "notebook", "image": "jupyter/singleuser:latest", "imagePullPolicy": "IfNotPresent",