Day 35- Mastering ConfigMaps and Secrets in Kubernetes

Day 35- Mastering ConfigMaps and Secrets in Kubernetes

ConfigMaps in K8S:

A ConfigMap is an API object that allows you to store and manage configuration data separately from your application code. It provides a way to decouple configuration details from your containerized applications, making it easier to manage and update configuration settings without modifying the application itself.

ConfigMap can store key-value pairs or be used to mount configuration files as volumes within your containers. This makes it convenient to manage different configurations for different environments (such as development, staging, and production) or to share common configuration settings across multiple containers.

To create a ConfigMap, you can define it using a YAML or JSON manifest file and then apply it to your Kubernetes cluster using the kubectl apply command. Here's an example of a simple ConfigMap in YAML format:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: my-container
      image: my-image
      env:
        - name: KEY1
          valueFrom:
            configMapKeyRef:
              name: my-config
              key: key1
        - name: KEY2
          valueFrom:
            configMapKeyRef:
              name: my-config
              key: key2

Why we use configmaps in k8s?

  1. Separation of concerns: Enable a separation of configuration data from application code. you can modify them without changing or redeploying your application containers. This separation simplifies the management of configuration and allows for more flexibility in different environments.

  2. Environment-specific configuration: Allow you to define different sets of configuration values for different environments, such as development, staging, and production. making it easier to promote applications across different stages of the development lifecycle.

  3. Centralized configuration management: Provide a centralized and consistent way to manage configuration settings for multiple containers or pods. Rather than duplicating configuration files or settings within each container, you can define a single ConfigMap and mount it as a volume across multiple containers or pods. This simplifies the management and updates of configuration settings.

  4. Dynamic configuration updates: ConfigMaps support dynamic updates, allowing you to modify configuration values at runtime without restarting or redeploying your application containers. This feature is particularly useful for applications that need to adapt to changing configuration settings without interrupting their operation.

  5. Sharing configuration across containers: ConfigMaps can be used to share common configuration settings across multiple containers within a pod. This is especially valuable in cases where multiple containers in a pod need to access the same configuration data or when containers require inter-container communication based on shared configuration values.

  6. Integration with other Kubernetes resources: ConfigMaps can be referenced by other Kubernetes resources, such as deployments, stateful sets, and pods. This allows you to inject configuration settings into these resources, making them configurable and adaptable to different environments or specific requirements.

Commands for Configuring Configmap in Kubernetes:

#List Configmap
kubectl get configmap
kubectl get cm
# Create Configmap from the file:
kubectl create configmap <configmap-name> --from-file=<path-to-file>
# Create Configmap from literals
kubectl create configmap <configmap-name> --from-literals=<key1=value1,key2=value2>
# Create Configmap from the directory:
kubectl create configmap <configmap-name> --from-file=<path-to-dirctory>
# Edit Configmap
kubectl edit configamp <configmap-name>
# View the data stored in Configmap
kubectl get configmap <configmap-name> -o yaml
 # Delete a Configmap
kubectl delete configmap <configmap-name>

Secrets in K8S:

Secrets are a type of API object used to store sensitive information, such as passwords, API keys, and TLS certificates. Secrets are designed to keep sensitive data secure and separate from the rest of the application configuration. Secrets are specifically intended for storing confidential data and have additional security measures in place.

Here are some key features and use cases of Secrets in Kubernetes:

  1. Sensitive data storage: Secrets serve as a secure storage mechanism for sensitive data, including passwords, access tokens, SSH keys, and TLS certificates. By utilizing Secrets, you can avoid storing sensitive information directly in your application code or configuration files, reducing the risk of exposing confidential data.

  2. Encryption at rest: Secrets are encrypted at rest within the Kubernetes cluster. This ensures that even if an attacker gains access to the cluster's storage, they will not be able to read the stored secret values in plain text.

  3. Access control: Secrets can be accessed and used only by authorized entities within the cluster. Kubernetes provides role-based access control (RBAC) mechanisms to control who can create, read, update, or delete Secrets. This helps enforce strong access controls and limit the exposure of sensitive information.

  4. Secure transmission: Secrets are transmitted securely between the API server and the nodes in the cluster. This protects the confidentiality of secret data during transit and prevents eavesdropping or tampering.

  5. Integration with pods: Secrets can be mounted as volumes within pods, similar to ConfigMaps. This allows containers within the pods to access the sensitive data directly as files. For example, you can mount a TLS certificate stored in a Secret to enable secure communication between containers or between containers and external services.

  6. Environment variables: Secrets can also be exposed as environment variables within containers. This enables easy access to secret values as environment variables, making it convenient for applications to consume sensitive information.

To create a Secret, you can define it using a YAML or JSON manifest file and then apply it to your Kubernetes cluster using the kubectl apply command. The secret data is typically base64-encoded to maintain secrecy. Here's an example of a Secret manifest:

apiVersion: v1
kind: Secret
metadata:
  name: my-secret
type: Opaque
data:
  username: dXNlcm5hbWU=
  password: cGFzc3dvcmQ=

Types of Secrets:

Kubernetes supports two types of Secrets:

a) Opaque : Opaque Secrets are the most common type and can store arbitrary key-value pairs.

b) Service Account Token: Service Account Token Secrets are automatically created for each service account in Kubernetes and contain credentials used for authenticating with the Kubernetes API server.

Commands for Kubernetes Secrets:

#List the Services #
kubectl get secrets
# Create a Secret from literal values #
kubectl create secret generic <secret-name> --from-literal=key1=value1 --from-literal=key2=value2
# Create a Secret from files #
kubectl create secret generic <secret-name> --from-file=path/to/file
# Create a Secret from an envirnoment files #
kubectl create secret generic <secret-name> --from-env-file=path/to/env/file
# Create a generic Secret and interactively enter key-value pairs #
kubectl create secret generic <secret-name> --dry-run=client -o yaml | kubectl apply -f -
# View details of a Secret #
kubectl describe secret <secret-name>
# Decode and view the content of a specific key in a Secret #
kubectl get secret <secret-name> -o jsonpath='{.data.key}' | base64 --decode
# Edit a Secret #
kubectl edit secret <secret-name>
# Delete a Secret #
kubectl delete secret <secret-name>

Task 1:

  • Create a ConfigMap for your Deployment

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

  • Update the deployment.yml file to include the ConfigMap

  • Apply the updated deployment using the command: kubectl apply -f deployment.yml -n <namespace-name>

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

    Create a ConfigMap for your Deployment:

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

Update the deployment.yml file to include the ConfigMap

  •   apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: mysql-deployment
        namespace: deployment
        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 configmap.yml
        kubectl get configmap -n <namespace> #To verify the ConfigMap creation
    

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

Task 2:

  • Create a Secret for your Deployment

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

  • Update the deployment.yml file to include the Secret

  • Apply the updated deployment using the command: kubectl apply -f deployment.yml -n <namespace-name>

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

Create a Secret for your Deployment

apiVersion: v1
kind: Secret
metadata:
  name: my-secret
  namespace: deployment
  labels: 
    app: mysql
type: Opaque
data:
  MYSQL_PASSWORD: "cm9vdAo="

In the above key pair the value of MYSQL_PASSWORD is the encoded password so below is the command to encode or decode the password to create the secret

Base64 encoding is commonly used in various applications, such as encoding binary attachments in email messages, embedding binary data in XML or JSON documents, and representing binary data in URL parameters when it might otherwise be restricted to text-only characters.

echo <password> | base64      ## To encode the password
echo <encoded_password> | base64 -d  ## To decode the password

Update the deployment.yml file to include the Secret

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql-deployment
  namespace: deployment
  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: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: my-secret
                  key: MYSQL_PASSWORD

Apply the updated deployment using the command: kubectl apply -f deployment.yml -n <namespace-name>

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

Both Secrets and ConfigMaps play a vital role in managing configuration and sensitive data within Kubernetes deployments. By utilizing these resources, you can separate configuration concerns from application code, enhance security by protecting sensitive information, and enable dynamic configuration updates without redeploying applications.

Thank you for 📖reading my blog, 👍Like it and share it 🔄 with your friends.

Happy learning😊😊 !!!