Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure kubernetes - python to read configmap?

I am trying to Dockerize the python application and want to read the configuration settings from the configmap. How do I read configmap in python?

like image 797
Karthikeyan Vijayakumar Avatar asked Oct 09 '20 05:10

Karthikeyan Vijayakumar


People also ask

How do I read a ConfigMap in Kubernetes?

The contents of the ConfigMap can be viewed with the kubectl describe command. Note that the full contents of the file are visible and that the key name is, in fact, the file name, max_allowed_packet. cnf. A ConfigMap can be edited live within Kubernetes with the kubectl edit command.

How do you read a pod ConfigMap?

Mount the ConfigMap through a Volume Attach to the created Pod using `kubectl exec -it pod-using-configmap sh`. Then run `ls /etc/config` and you can see each key from the ConfigMap added as a file in the directory. Use `cat` to look at the contents of each file and you'll see the values from the ConfigMap.


2 Answers

Create a configMap with the configuration file:

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

Mount the configMap in your Pod's container and use it from your application:

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

Now, your config file will be available in /config-directory/my-config.file. You can read it from your Python code like below:

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

You can also use configMap's data as the container's env - Define container environment variables using configMap data

config = os.environ['MY_CONFIG']
like image 110
Kamol Hasan Avatar answered Oct 20 '22 22:10

Kamol Hasan


When creating an app for Kubernetes, it is good to follow the The Twelve Factor App principles. There is one item about Config that recommends to store environment specific app settings as environment variables.

In Python environment variables can be read with os.environ, example:

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

And you can create those environment variables using kubectl with:

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

I would recommend to handle your environment settings with kubectl kustomize as described in Declarative Management of Kubernetes Objects Using Kustomize, especially with the configmapGenerator and apply them to different environments with:

kubectl apply -k <environment>/
like image 1
Jonas Avatar answered Oct 20 '22 22:10

Jonas