【问题标题】:Azure kubernetes - python to read configmap?Azure kubernetes - python 读取配置映射?
【发布时间】:2021-01-24 04:33:48
【问题描述】:

我正在尝试对 python 应用程序进行 Dockerize 化,并希望从 configmap 中读取配置设置。如何在 python 中读取 configmap?

【问题讨论】:

    标签: python azure kubernetes configmap


    【解决方案1】:

    使用配置文件创建一个configMap:

    $ kubectl create configmap my-config --from-file my-config.file
    

    在您的 Pod 容器中安装 configMap 并在您的应用程序中使用它:

            volumeMounts:
            - name: config
              mountPath: "/config-directory/my-config.file"
              subPath: "my-config.file"
          volumes:
            - name: config
              configMap:
                name: my-config
    

    现在,您的配置文件将在/config-directory/my-config.file 中可用。您可以从您的 Python 代码中读取它,如下所示:

    config = open("/config-directory/my-config.file", "r")
    

    您也可以使用 configMap 的数据作为容器的环境 - Define container environment variables using configMap data

    config = os.environ['MY_CONFIG']
    

    【讨论】:

    • 谢谢。如何在 python 中读取这个配置文件?
    • @KarthikeyanVijayakumar 与从本地目录或环境变量中读取文件的方式相同。
    • @KamolHasan 你能帮我解决这个问题吗:stackoverflow.com/questions/66450175/…
    【解决方案2】:

    在为 Kubernetes 创建应用程序时,最好关注The Twelve Factor App principles。关于Config 有一项建议将特定于环境的应用设置存储为环境变量

    在Python环境变量可以用os.environ读取,例如:

    import os
    print(os.environ['DATABASE_HOST'])
    print(os.environ['DATABASE_USER'])
    

    您可以使用kubectl 创建这些环境变量:

    kubectl create configmap db-settings --from-literal=DATABASE_HOST=example.com,DATABASE_USER=dbuser
    

    我建议使用kubectl kustomize 处理您的环境设置,如Declarative Management of Kubernetes Objects Using Kustomize 中所述,尤其是使用configmapGenerator 并将它们应用于不同的环境:

    kubectl apply -k <environment>/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 2019-04-30
      • 2018-10-31
      • 2018-02-21
      相关资源
      最近更新 更多