Kubernetes Secrets: A complete guide to securely managing sensitive information

Kubernetes Secrets
Kubernetes Secrets

Introduction

In a container orchestration system, safeguarding and effectively managing sensitive information like passwords, API keys, and other confidential data is paramount. Kubernetes offers a robust solution through its Secrets feature, designed to handle sensitive information securely, centrally, and with precise control.

This article delves deeply into the fundamental principles, advantages, drawbacks, creation, updating procedures, and practical usage of Kubernetes Secrets. Additionally, it provides actionable suggestions for optimal implementation and management of Secrets within a Kubernetes environment.

Kubernetes Secrets Principle

  • Secrets store sensitive information such as passwords, API keys, etc. in base64-encoded form.
  • It is stored in etcd, but will undergo a layer of base64 encoding to improve the security of the information.

Kubernetes Secrets Advantage

  • Improved security: Improved protection of sensitive information through base64 encoding and centralized management.
  • Centralized management: Sensitive information is stored centrally for easy management and updates.
  • Version control: Can be associated with a specific version of a Pod to achieve precise control and tracking of access rights.

Kubernetes Secrets Limitations

  • Limited security: base64 encoding provides a simple obfuscation rather than true encryption.
  • Simple permission management: Relatively simple permission management may not be enough to meet the needs of some scenarios.

Create and update Kubernetes Secrets

Create Secrets from text

kubectl create secret generic db-credentials \
  --from-literal=username=myuser \
  --from-literal=password=mypassword

Create Secrets from files

Assume secrets.txt the file contains the following content:

username=myuser
password=mypassword
kubectl create secret generic db-credentials --from-file=secrets.txt

Directly update Secrets (the example is only for demonstration, it is not recommended to update directly in the production environment)

kubectl create secret generic db-credentials \
  --from-literal=username=newuser \
  --from-literal=password=newpassword \
  --dry-run=client -o yaml | kubectl apply -f -

Update Secrets from files

Assume secrets_updated.txt the file contains the following content:

username=newuser
password=newpassword
kubectl create secret generic db-credentials --from-file=secrets_updated.txt --dry-run=client -o yaml | kubectl apply -f -

Use Kubernetes Secrets

Using Secrets in Pods

An in-depth discussion of how to reference Secrets in Pod configuration files and use valueFrom and secretKeyRef to obtain sensitive information from Secrets. For example, use the above database credential Secret in the Pod:

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mycontainer
    image: myimage
    env:
    - name: DB_USERNAME
      valueFrom:
        secretKeyRef:
          name: db-credentials
          key: username
    - name: DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: db-credentials
          key: password

An in-depth discussion of how to reference Secrets in Pod configuration files and use valueFrom and secretKeyRef to obtain sensitive information from Secrets. Here are examples of reading configuration in Java, Python and Node.js applications:

Java application

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class MyApp {
     public static void main(String[] args) throws Exception {
         //Read database credentials from Secrets
         String usernameSecret = System.getenv("DB_USERNAME");
         String passwordSecret = System.getenv("DB_PASSWORD");

         // Decode base64 encoded credentials
         String decodedUsername = new String(Base64.getDecoder().decode(usernameSecret));
         String decodedPassword = new String(Base64.getDecoder().decode(passwordSecret));

         // Use credentials to connect to the database or perform other sensitive operations
         // ...
     }
}

Python applications

import os
import base64

# Read database credentials from Secrets
username_secret = os.environ.get("DB_USERNAME")
password_secret = os.environ.get("DB_PASSWORD")

# Decode base64 encoded credentials
decoded_username = base64.b64decode(username_secret).decode('utf-8')
decoded_password = base64.b64decode(password_secret).decode('utf-8')

# Use credentials to connect to the database or perform other sensitive operations
#...

Node.js application

const { DB_USERNAME, DB_PASSWORD } = process.env;

//Read database credentials from Secrets
const usernameSecret = DB_USERNAME;
const passwordSecret = DB_PASSWORD;

// Decode base64 encoded credentials
const decodedUsername = Buffer.from(usernameSecret, 'base64').toString('utf-8');
const decodedPassword = Buffer.from(passwordSecret, 'base64').toString('utf-8');

// Use credentials to connect to the database or perform other sensitive operations
// ...

These examples show how to read Kubernetes Secrets in applications in different languages ​​and decode and use this sensitive information in the application. In this way, you can ensure that sensitive information is safely passed into the application.

Practical Suggestions

Some suggestions are provided for readers, including best practices such as avoiding hard-coding sensitive information and rotating sensitive information regularly, to help them better apply Secrets to actual production environments.

Cleanup and best practices

Introduces how to safely clean up Secrets that are no longer needed and some best practices for using Secrets to ensure the robustness and security of the system.

  • Clean up Secrets no longer needed:
kubectl delete secret db-credentials
  • Regular rotation of sensitive information:

Define an automated task, such as a CronJob, to regularly create new Secrets and update related applications to ensure that old credentials are no longer valid. 

For example, to rotate database credentials monthly:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: rotate-db-credentials
spec:
  schedule: "0 0 1 * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: rotate
            image: rotate-image
            command: ["rotate-script.sh"]

🔥 [20% Off] Linux Foundation Coupon Code for 2024 DevOps & Kubernetes Exam Vouchers (CKAD , CKA and CKS) [RUNNING NOW ]

Save 20% on all the Linux Foundation training and certification programs. This is a limited-time offer for this month. This offer is applicable for CKA, CKAD, CKSKCNALFCS, PCA FINOPSNodeJSCHFA, and all the other certification, training, and BootCamp programs.

Coupon Ends Soon ... ⏳
Kubernetes Application Developer (CKAD)

$395 $316


  • Upon registration, you have ONE YEAR to schedule and complete the exam.
  • The CKA exam is conducted online and remotely proctored.
  • To pass the exam, you must achieve a score of 66% or higher.
  • The CKAD Certification remains valid for a period of 3 years.
  • You are allowed a maximum of 2 attempts to take the test. However, if you miss a scheduled exam for any reason, your second attempt will be invalidated.
  • Free access to killer.sh for the CKAD practice exam.


CKAD Exam Voucher: Use coupon Code TECK20 at checkout


We earn a commission if you make a purchase, at no additional cost to you.
Coupon Ends Soon ... ⏳
Certified Kubernetes Administrator (CKA)

$395 $316



  • Upon registration, you have ONE YEAR to schedule and complete the exam.
  • The CKA exam is conducted online and remotely proctored.
  • To pass the exam, you must achieve a score of 66% or higher.
  • The CKA Certification remains valid for a period of 3 years.
  • You are allowed a maximum of 2 attempts to take the test. However, if you miss a scheduled exam for any reason, your second attempt will be invalidated.
  • Free access to killer.sh for the CKA practice exam.


CKA Exam Voucher: Use coupon Code TECK20 at checkout

We earn a commission if you make a purchase, at no additional cost to you.
Coupon Ends Soon ... ⏳
Certified Kubernetes Security Specialist (CKS)

$395 $316



  • Upon registration, you have ONE YEAR to schedule and complete the exam.
  • The CKA exam is conducted online and remotely proctored.
  • To pass the exam, you must achieve a score of 67% or higher.
  • The CKS Certification remains valid for a period of 2 years.
  • You are allowed a maximum of 2 attempts to take the test. However, if you miss a scheduled exam for any reason, your second attempt will be invalidated.
  • Free access to killer.sh for the CKS practice exam.


CKS Exam Voucher: Use coupon Code TECK20 at checkout


We earn a commission if you make a purchase, at no additional cost to you.

Check our last updated Kubernetes Exam Guides (CKAD , CKA , CKS) :

Conclusion

Summarizes the key concepts and practices of Kubernetes Secrets, emphasizing the importance of securely managing sensitive information in containerized environments. 

Through this article, readers will have a more comprehensive understanding of how to effectively use Kubernetes Secrets to ensure the security and stability of applications and systems.

Author

  • Mohamed BEN HASSINE

    Mohamed BEN HASSINE is a Hands-On Cloud Solution Architect based out of France. he has been working on Java, Web , API and Cloud technologies for over 12 years and still going strong for learning new things. Actually , he plays the role of Cloud / Application Architect in Paris ,while he is designing cloud native solutions and APIs ( REST , gRPC). using cutting edge technologies ( GCP / Kubernetes / APIGEE / Java / Python )

    View all posts
0 Shares:
You May Also Like