Hello you! Today, I thought I can share a solution to a problem I was facing. I specifically wanted the configmaps/secrets as files and my code will just use those files. After almost two days, I got this working, so thought I can share it with you on how to attach ConfigMaps and Secrets as files in a Kubernetes Pod. This is a common requirement when you want to use the configs/secrets as files so you just interact with them as files.
ConfigMaps
They are useful for storing non-sensitive data ( this is because they are stored in plain text whereas secrets are encoded ) .
Here’s a sample ConfigMap,
apiVersion: v1
kind: ConfigMap
metadata:
name: user-cm
data:
user.input: |
shajith=100
This ConfigMap can be mounted into a Pod using a Volume:
apiVersion: v1
kind: Pod
metadata:
name: user
spec:
containers:
- name: user-container
image: user-image
volumeMounts:
- name: config-volume
mountPath: user.input
volumes:
- name: config-volume
configMap:
name: user-cm
In this example, you would see a file named user.input in the root directory of this pod ( we can also mention the complete path to the “mountPath” property ).
To note: We can use the key names as the file names like .env, development.json, etc – this way the files created can be with better naming convention, more importantly it will help in pointing to the right file.
MountPath mounts a complete volume, but if you want to mount only one folder,or subdirectory you can use subPath.
To Note: While using subPath, it should match the filename mentioned in the mountPath.
Ex: MountPath: /app/.env
subPath: .env
This will mount to .env instead of mounting a complete volume.
Secrets
Kubernetes Secrets let you store and manage sensitive information. They say that because it is encoded.
Here’s a sample Secret.
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
username: YWRtaW4=
password: YWRtaW4=
As you can see the values are encoded.
This Secret can be mounted into a Pod using a Volume:
apiVersion: v1
kind: Pod
metadata:
name: db-pod
spec:
containers:
- name: db-container
image: db-image
volumeMounts:
- name: secret-volume
mountPath: /etc/secret
volumes:
- name: secret-volume
secret:
secretName: db-secret
In this example, username
and password
from the db-secret
Secret are mounted into the db-container
at the paths /etc/secret/username
and /etc/secret/password
respectively.
As you will see, it creates two files named “username” and “password” and you can check the values, being present inside the files.
Conclusion
ConfigMaps and Secrets are kubernetes objects, that separates from your main code. And this approach takes it one step further by adding them as files directly.
This can be a security concern for some, because the containers will have these files which may or may not have highly sensitive information stored in them.
Feel free to reach out to me if you have any questions. I would love to help if at all possible.
See you around!