In Kubernetes, ConfigMap is a valuable tool that allows you to store configuration data separately from the application code. This separation enables you to manage configuration data effectively, and modify it without having to rebuild the application. In this article, we will learn how to create a ConfigMap from a properties file using K8s client.
Before we start, make sure that you have the K8s client installed on your local machine and have access to a Kubernetes cluster.
Step 1: Create a Properties File
The first step is to create a properties file that contains the configuration data you want to store in the ConfigMap. For example, let's say we want to store the database credentials in the ConfigMap. We can create a properties file named
db.properties with the following content:
Step 2: Create a ConfigMap from the Properties File
Now that we have the properties file, we can create a ConfigMap from it using the K8s client. The following command will create a ConfigMap named
db-config from the
kubectl create configmap db-config --from-file=db.properties
You can verify that the ConfigMap has been created by running the following command:
kubectl get configmap db-config -o yaml
This will output the YAML representation of the ConfigMap.
Step 3: Use the ConfigMap in a Pod
Now that we have created the ConfigMap, we can use it in a Pod. Here is an example YAML file that demonstrates how to use the ConfigMap in a Pod:
- name: my-container
- name: DB_HOST
- name: DB_PORT
- name: DB_USER
- name: DB_PASSWORD
In this example, we are creating a Pod with a single container. We have defined four environment variables that correspond to the database credentials. Each environment variable uses the
valueFrom field to reference the ConfigMap we created earlier.
Step 4: Verify the Pod
To verify that the Pod is using the ConfigMap, you can run the following command:
kubectl exec my-pod -- printenv
This will output the environment variables for the container. You should see the four database credentials variables that we defined earlier.
Congratulations! You have successfully created a ConfigMap from a properties file using K8s client and used it in a Pod.
- You can create a ConfigMap from a directory containing multiple properties files using the
--from-fileoption followed by a directory path.
- You can create a ConfigMap from literal values using the
--from-literaloption followed by key-value pairs.
Related Searches and Questions asked:
That's it for this post. Keep practicing and have fun. Leave your comments if any.