首页 > 解决方案 > 在 Jupyterhub 中将 k8s secret 中的环境变量添加到 notebook

问题描述

我正在使用Zero to Jupyterhub Helm 包来将 Jupyterhub 部署到我们的 kubernetes 集群中。单个笔记本图像需要一些额外的环境变量(主要是数据库连接信息),我希望它们从 k8s 命名空间中的现有秘密中提取值。我该怎么做呢?

使用以下配置的天真方法不起作用:

singleuser:
  extraEnv:
    SECURE_ENVIRONMENT_VARIABLE: 
      valueFrom:
        secretKeyRef:
          name: secret
          value: key

结果SECURE_ENVIRONMENT_VARIABLE被设置为map[valueFrom:map[secretKeyRef:map[name:secret value:key]]].

我也尝试过按照KubeSpawner config docssingleuser.extraConfig进行设置,但是如果你使用它来设置它显然会覆盖现有的环境变量,这会破坏系统:c.KubeSpawner.extra_container_configenv

extraConfig: |
    c.KubeSpawner.extra_container_config = {
      "env": [
        {
          "name": "SECURE_ENVIRONMENT_VARIABLE",
          "value": "test" # even a hardcoded value results in the container failing 
        }
      ]
    }

作为记录,我可以通过创建部署 .yamlhelm upgrade --debug --dry-run并在必要时手动编辑它,我只是不知道如何将此信息获取到动态生成的 pod 上。

标签: jupyterhub

解决方案


在这里https://github.com/jupyterhub/kubespawner/issues/306#issuecomment-474934945 我提供了使用非字符串值设置环境变量的解决方案。

基本思想是使用 c.KubeSpawner.modify_pod_hook 将变量添加到 pod 规范中。


hub:
  extraConfig:
    ipaddress: |
      from kubernetes import client

      def modify_pod_hook(spawner, pod):
          pod.spec.containers[0].env.append(client.V1EnvVar("MY_POD_IP", None, client.V1EnvVarSource(None, client.V1ObjectFieldSelector(None, "status.podIP"))))
          return pod
      c.KubeSpawner.modify_pod_hook = modify_pod_hook

推荐阅读