Mastering ConfigMaps and Secrets in Kubernetes

Mastering ConfigMaps and Secrets in Kubernetes

·

7 min read

In yesterday's blog, I got some hands on the services in Kubernetes. Let's move forward today and learn and master ConfigMaps and Secrets in Kubernetes.

ConfigMaps

According to kubernetes.io, a ConfigMap is an API object used to store non-confidential data in key-value pairs.

ConfigMaps are used to store configuration data that can be consumed by pods or other Kubernetes resources.

ConfigMaps are typically used to store non-sensitive configuration data such as environment variables, command-line arguments, or configuration files. This data can be accessed by pods as environment variables or mounted as files.

A ConfigMap is not designed to hold large chunks of data. The data stored in a ConfigMap cannot exceed 1 MiB.

There are four different ways that you can use a ConfigMap to configure a container inside a Pod:

  1. Inside a container command and args

  2. Environment variables for a container

  3. Add a file in read-only volume, for the application to read

  4. Write code to run inside the Pod that uses the Kubernetes API to read a ConfigMap

Secrets

According to kubernetes.io, a Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key.

Secrets are used to store sensitive information such as passwords, API keys, and TLS certificates. Secrets provide a secure way to store and manage this confidential data within a cluster. They are similar to ConfigMaps but are specifically designed to handle sensitive information.

There are three main ways for a Pod to use a Secret:

Difference between ConfigMaps and Secrets in Kubernetes

CriteriaConfigMapsSecrets
PurposeStore non-sensitive configuration data.Store sensitive information.
Data TypesText files, key-value pairs, or environment variables. ConfigMaps store data as plain textText files, key-value pairs, or environment variables. Secrets can store data as base64-encoded or opaque.
Data VisibilityData is visible in plain text to anyone with access.Data is encrypted and stored securely.
Use CasesConfiguration files, environment variables, and command-line options.Passwords, API keys, TLS certificates, secrets.
SecurityNo encryption or protection of data.Data is encrypted and stored securely.
Accessing DataAccessed as environment variables or mounted as files.Accessed as environment variables or mounted as files.
Update DynamicsChanges require pod restarts to take effect.Changes are dynamically updated without pod restarts.
NamespacesConfigMaps can be shared across namespaces.Secrets are limited to a single namespace.
Kubernetes ObjectsConfigMaps are represented as ConfigMap objects.Secrets are represented as Secret objects.
CreationData is provided directly in the YAML file or from files.Data is provided directly in the YAML file or from files.
Access ControlConfigMaps have no built-in access control mechanisms.Secrets can be granted specific access controls.
Use in PodsConfigMaps can be used in any pod.Secrets are primarily used by pods for sensitive data.
Volume MountsConfigMaps can be mounted as volumes in pods.Secrets can also be mounted as volumes in pods.
Data SizeConfigMaps can store larger amounts of data.Secrets have size limitations based on the backend storage.
Backup and RestoreConfigMaps are easily backed up and restored.Secrets require additional security measures for backup and restoration.
Data ModificationConfigMap data can be modified without restarting pods.Secrets require pod restarts for data modification.

Let's start with the tasks now to learn and master ConfigMaps and Secrets.

Tasks

Task 1: Create a ConfigMap for your Deployment

Let's create a mysql-config.yml file.

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
  labels:
    app: django-todo-app
  namespace: deploy1
data:
  MYSQL_DB: "database_todo"

This YAML file creates a ConfigMap object that stores a single configuration setting, MYSQL_DBwith the value "database_todo". This ConfigMap can be used by a pod in the deploy1 namespace to access this configuration setting as an environment variable or a file in a mounted volume.

Now apply the configmap.yml file to your deployment.

kubectl apply -f configmap.yml

To verify the ConfigMap creation, use the following command:

kubectl get configmap -n <namespace>

And yes! The ConfigMap is created successfully.

Task 2: Create a Secret for your Deployment

Before jumping into creating Secrets, let us encrypt the username and password.

I am taking the following details:

Password: admin@123

In your terminal, using base64 you can encode and decode:

echo -n 'admin@123' | base64

You can verify the encrypted characters by using the following:

echo YWRtaW5AMTIz | base64 --decode

What is base64? Base64 is a binary-to-text encoding scheme that represents binary data in sequences of 24 bits that can be represented by four 6-bit Base64 digits.

It is always better to not use hardcoded values for data like usernames and passwords.

I am going to use these encoded characters in the mysql-secret.yml file that I am going to create now.

apiVersion: v1
kind: Secret
metadata:   
  name: my-secret
  namespace: deploy1
type: Opaque
data:
  password: YWRtaW5AMTIz

This YAML file creates a Secret object that stores a single piece of sensitive data, passwordwith the value admin@123. This Secret can be used by a pod in the deploy1 namespace to access this sensitive data as an environment variable or a file in a mounted volume. The value is encoded in base64 format to protect it from being exposed accidentally or stored in a terminal log.

What's the type: Opaque mentioned here in the above code block?

In Kubernetes, type: Opaque is the default type for a Secret object.It means that the contents of the Secret are unstructured and can contain arbitrary key-value pairs.

Opaque Secrets are used to store arbitrary user-defined data, such as passwords, OAuth tokens, and ssh keys.

Other types of Secrets include: Service accounts token secrets (store a token that references a service account.), Docker registry secrets (store credentials for accessing a Docker registry), and TLS secrets (store TLS certificates and keys).

Let's apply the secret to deployment.

kubectl apply -f mysql-secret.yml -n <namespace>

We can verify the creation of secrets using:

kubectl get secrets -n <namespace>

Update the sqldeployment.yml with the secrets and config map.

 apiVersion: apps/v1
 kind: Deployment
 metadata:
   name: mysql-configuration
   labels:
     app: mysql
   namespace: deploy1 
 spec:
   replicas: 2
   selector:
     matchLabels:
       app: mysql
   template:
     metadata:
       labels:
         app: mysql
     spec:
       containers:
       - name: mysql-container
         image: mysql:8
         ports:
         - containerPort: 3306
         env:
         - name: MYSQL_ROOT_PASSWORD
           valueFrom:
             secretKeyRef:
               name: my-secret
               key: password
         - name: MYSQL_DATABASE
           valueFrom:
             configMapKeyRef:
               name: my-configmap
               key: MYSQL_DB

Let's apply this to the cluster.

kubectl apply -f sqldeployment.yml -n deploy1

Let's verify if the pods are running.

kubectl get pods -n <namespace>

And yes, the pods are created.

But we need to use the MySQL service. For that, we will have to expose the k8s cluster to a port. I will create a sqlservice.yml for that.

 apiVersion: v1
 kind: Service
 metadata:
   name: mysql-service-configuration
 spec:
   ports:
   - name: mysql
     port: 3306
   clusterIP: None
   selector:
     app: mysql

And apply to the cluster.

kubectl apply -f sqlservice.yml -n <namespace>

Get inside the worker node and install the MYSQL client.

 sudo apt install mysql-client-core-8.0

Now on the controller, connect to any node:

kubectl exec -it mysql-configuration-858b8c57ff-p52wz /bin/sh -n deploy1

Connect using the username and password you gave in the secret.yml file.

 mysql -u root -p${MYSQL_ROOT_PASSWORD}

Now we are in the MYSQL console. We can see the databases in the container using show databases;

And yay we incorporated both ConfigMaps and Secrets in your deployment.


In this blog, I have incorporated both ConfigMaps and Secrets into my deployments in Kubernetes and how to create and manage them in this blog. If you have any questions or would like to share your experiences, feel free to leave a comment below. Don't forget to read my blogs and connect with me on LinkedIn and let's have a conversation.

To help me improve my blog and correct my mistakes, I am available on LinkedIn as Sneha K S. Do reach me and I am open to suggestions and corrections.

#Day35 #90daysofdevops

Did you find this article valuable?

Support Sneha K S by becoming a sponsor. Any amount is appreciated!