In this tutorial, we aim to guide you on how to configure your applications using ConfigMaps and Secrets in Kubernetes. The ultimate goal is to help you understand how to separate configuration data from application code, making your applications more flexible and secure.
By the end of this tutorial, you'll learn:
Prerequisites:
ConfigMaps and Secrets are Kubernetes API objects that allow you to store configuration for your applications separately from the application code.
ConfigMaps allow you to decouple configuration details from image content to keep containerized applications portable. They store non-confidential data in key-value pairs.
Secrets are used to save sensitive data, such as passwords, OAuth tokens, and ssh keys. Unlike ConfigMaps, Kubernetes offers some additional protection to Secret data.
You can create ConfigMaps using the kubectl
command-line interface or a ConfigMap manifest file (YAML or JSON).
kubectl create configmap example-config --from-literal=key1=value1 --from-literal=key2=value2
This command creates a new ConfigMap named example-config
with the key-value pairs key1=value1
and key2=value2
.
Similar to ConfigMaps, you can create Secrets using the kubectl
command-line interface or a Secret manifest file.
kubectl create secret generic example-secret --from-literal=username=myuser --from-literal=password=mypassword
This command creates a new Secret named example-secret
with the key-value pairs username=myuser
and password=mypassword
.
Let's now look at how to use these ConfigMaps and Secrets in your applications.
Using ConfigMaps
Here's an example of a Pod that uses values from example-config
to configure a container:
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mycontainer
image: myimage
env:
- name: KEY1
valueFrom:
configMapKeyRef:
name: example-config
key: key1
Using Secrets
Here's an example of a Pod that uses values from example-secret
to configure a container:
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mycontainer
image: myimage
env:
- name: USERNAME
valueFrom:
secretKeyRef:
name: example-secret
key: username
In this tutorial, we learned how to create and use ConfigMaps and Secrets in Kubernetes. We also looked at how to decouple configuration details from the application code, which leads to more flexible and secure applications.
To continue your learning journey, consider exploring more about Kubernetes, such as Persistent Volumes, Policies, and Kubernetes API resources.
Solutions:
Remember, practice is key to mastering any concept. Happy Learning!