ConfigMaps and Secrets in Kubernetes: Best Practices ๐Ÿ”’๐Ÿ”‘๐Ÿ›ก๏ธ

ConfigMaps and Secrets in Kubernetes: Best Practices ๐Ÿ”’๐Ÿ”‘๐Ÿ›ก๏ธ

ยท

7 min read

Introduction

In the intricate landscape of Kubernetes, efficient configuration management is a key to success. ConfigMaps and Secrets are powerful tools that play a pivotal role in storing and managing configuration data, whether non-sensitive or confidential. This guide will not only walk you through the fundamentals but also equip you with practical knowledge to implement these essential Kubernetes resources effectively.

What are ConfigMaps in K8s?

A ConfigMap is an API object utilized to store non-sensitive data in key-value pairs. It serves as a means to maintain configuration data that can be readily accessed by pods or other Kubernetes resources.

Typically, ConfigMaps are employed for storing non-confidential configuration details like environment variables, command-line arguments, or configuration files. This data can be made available to pods either as environment variables or mounted as files.

It is worth noting that a ConfigMap is not intended to hold large volumes of data; the stored information within a ConfigMap cannot exceed 1 MiB.

ConfigMaps offer four distinct methods for configuring a container within a Pod:

  1. Inside a container command and args: This method involves directly referencing ConfigMap values within the command or arguments of a container.

  2. Environment variables for a container: ConfigMap values can be set as environment variables for a container, allowing them to be accessed within the application.

  3. Add a file in a read-only volume, for the application to read: ConfigMap values can be mounted as files in a Pod's filesystem, enabling the application to read them.

  4. Write code to run inside the Pod that uses the Kubernetes API to read a ConfigMap: This method involves writing code within the Pod that interacts with the Kubernetes API to retrieve values from a ConfigMap.

For additional information, please refer to the documentation here.

What are Secrets in k8s?

Secrets in Kubernetes, serve as a secure means to store and manage sensitive information like passwords, tokens, or keys. They are specialized objects designed for safeguarding confidential data within a cluster.

Secrets enable you to securely pass this sensitive information to your applications without embedding them directly in your code or configuration files. They are crucial for maintaining the security of your applications in a Kubernetes environment.

There are several ways for a Pod to utilize a Secret:

  1. As environment variables: Secrets can be exposed as environment variables within a Pod, allowing applications to access sensitive information.

  2. As files in a volume: Secrets can be mounted as files in a Pod's filesystem, providing a secure way for applications to read confidential data.

  3. As an image pull secret: This type of secret allows Pods to pull private container images from container registries securely.

  4. As a service account token: Secrets can be automatically created for each service account in a namespace, providing a secure way for Pods to authenticate with the Kubernetes API.

For additional information, please refer to the documentation here.

Difference Between ConfigMaps and Secrets in Kubernetes

CriteriaConfigMapsSecrets
Data SensitivityNon-sensitive configuration dataSensitive information
Data TypesText files, key-value pairs, environment varsText files, key-value pairs, base64-encoded
Data VisibilityData is visible in plain text formatData is encrypted and stored securely
Use CasesConfiguration files, environment variablesPasswords, API keys, TLS certificates, secrets
SecurityNo encryption, data is plain textData is encrypted and stored securely
Accessing DataAccessed as environment variables, or filesAccessed as environment variables, or files
Update DynamicsRequires pod restarts for changes to take effectDynamically updated without pod restarts
NamespacesCan be shared across namespacesLimited to a single namespace
Kubernetes ObjectsRepresented as ConfigMap objectsRepresented as Secret objects
CreationData is provided directly in YAML or from filesData is provided directly in YAML or from files
Access ControlNo built-in access control mechanismsCan be granted specific access controls
Use in PodsCan be used in any podPrimarily used by pods for sensitive data
Volume MountsCan be mounted as volumes in podsCan be mounted as volumes in pods
Data SizeCan store larger amounts of dataSize limitations based on backend storage
Backup and RestoreEasily backed up and restoredRequires additional security measures for backup and restoration
PurposeStore non-sensitive configuration dataStore sensitive information

This detailed table provides a comprehensive overview of the differences between ConfigMaps and Secrets in Kubernetes, along with their specific characteristics and use cases.

Choosing Between ConfigMaps and Secrets in Kubernetes

CriteriaWhen to Use ConfigMapsWhen to Use Secrets
SensitivityNon-sensitive dataSensitive data
ConfidentialityInformation not requiring encryptionConfidential information requiring encryption
Data Size Limit< 1 MiB< 1 MiB
Example Use CasesConfiguration files, environment variablesPasswords, API keys, tokens, TLS certificates
EncryptionData is not encryptedData is encrypted at rest
Access ControlNo special handling for access controlRestricted access, only accessible by pods

Tasks:

Vector cartoon to do list icon in comic style. Checklist, task list sign  illustration pictogram. Reminder business splash effect concept. 16135978  Vector Art at Vecteezy

Task 1: Configuring a ConfigMap for Deployment

We use ConfigMap and Secret in Kubernetes to store configuration data and sensitive information like MySQL credentials securely.

  • Create a ConfigMap for your Deployment using a file or the command line

      apiVersion: v1
      kind: ConfigMap
      metadata:
        name: mysql-config
        namespace: mysql
        labels:
          app: mysql
    
      data:
        MYSQL_DATABASE: "cooldb"
    

    type: Opaque in a Kubernetes Secret signifies that the secret contains arbitrary, unstructured data without any specific interpretation by Kubernetes.

  • Update the deployment.yml file to include the ConfigMap

      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: mysql-deployment
        namespace: mysql
        labels:
          app: mysql
    
      spec:
        replicas: 1
        selector:
          matchLabels:
            app: mysql
    
        template:
          metadata:
            labels:
              app: mysql
    
          spec:
            containers:
              - name: mysql
                image: mysql:8
                ports:
                - containerPort: 3306
                env:
                  - name: MYSQL_DATABASE
                    valueFrom:
                      configMapKeyRef:
                        name: mysql-config
                        key: MYSQL_DATABASE
    
  • Apply the updated deployment using the command: kubectl apply -f deployment.yml -n <namespace-name>

       kubectl apply -f deployment.yaml
    

  • Verify that the ConfigMap has been created by checking the status of the ConfigMaps in your Namespace.

      kubectl get configmap -n mysql
    

Task 2: Creating and Using a Secret in Your Deployment

Before jumping into creating Secrets

  1. Password Encryption: Begin by ensuring the security of sensitive information. For instance, let's take the password test@123 as an example.

  2. Base64 Encoding: Utilize the base64 encoding method to encrypt the data, enhancing its protection.

  3. Terminal Command: Execute the following command in your terminal to perform the encryption: echo -n 'test@123' | base64.

     echo -n 'test@123' | base64
     # The -n option ensures that no trailing newline character is added to the string before encoding.
    
    • Create a Secret for your Deployment using a file or the command line

        apiVersion: v1
        kind: Secret
        metadata:
          name: mysql-secret
          namespace: mysql
          labels:
            app: mysql
      
        type: Opaque
        data:
          MYSQL_PASSWORD: dGVzdEAxMjM=
      

    • Update the deployment.yml file to include the Secret

        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: mysql-deployment
          namespace: mysql
          labels:
            app: mysql
      
        spec:
          replicas: 1
          selector:
            matchLabels:
              app: mysql
      
          template:
            metadata:
              labels:
                app: mysql
      
            spec:
              containers:
                - name: mysql
                  image: mysql:8
                  ports:
                  - containerPort: 3306
                  env:
                    - name: MYSQL_DATABASE
                      valueFrom:
                        configMapKeyRef:
                          name: mysql-config
                          key: MYSQL_DATABASE
                    - name: MYSWL_ROOT_PASSWORD
                      valueFrom:
                        secretKeyRef:
                          name: mysql-secret
                          key: MYSQL_ROOT_PASSWORD
      
    • Apply the updated deployment using the command: kubectl apply -f deployment.yml -n <namespace-name>

         kubectl apply -f deployment.yaml
      

    • Verify that the Secret has been created by checking the status of the Secrets in your Namespace.

         kubectl get secrets -n <namespace>
      

Conclusion

Congratulations on mastering ConfigMaps and Secrets in Kubernetes! You're now equipped to manage configuration settings and secure sensitive information effectively in your deployments. Use these tools to fine-tune your applications, making sure they perform smoothly in ever-changing environments.


To learn more about creating Kubernetes Secrets using kubectl and other methods go through this LINK


Thank you for diving into this blog with me! I trust you found the information both helpful and enlightening. To stay updated on the latest in DevOps ๐Ÿš€, make sure to follow me. Remember, staying informed means staying ahead in the dynamic world of DevOps!

Feel free to connect with me on LinkedIn for more updates and discussions on DevOps and Kubernetes! ๐Ÿš€

Happy Learning! Keep pushing those boundaries! ๐Ÿ˜Š

ย