๐Ÿ”’ Security

Sealed Secrets

Encrypted secret management in Kubernetes: a Bitnami open-source tool for safe secret storage in GitOps environments

๐Ÿ“– Detailed Explanation

Sealed Secrets is a Kubernetes secret encryption tool developed by Bitnami. It solves the biggest challenge in GitOps environments: "how to safely store secrets in Git." A regular Kubernetes Secret is only base64-encoded, so it is effectively plaintext, but when you use Sealed Secrets, it is encrypted with a public key and can be decrypted only by the Sealed Secrets Controller inside the cluster.

It works on the basis of asymmetric encryption (public key/private key). The Controller installed in the cluster holds the private key, and developers encrypt a Secret with the public key through the kubeseal CLI tool to create a SealedSecret resource. This SealedSecret can be stored safely in Git, and when it is deployed to the cluster, the Controller automatically decrypts it and creates the actual Secret.

The biggest advantage of Sealed Secrets is its seamless integration with existing Kubernetes workflows. When used together with GitOps tools such as ArgoCD and Flux, the entire infrastructure can be managed as code. In addition, scopes can be specified per namespace or per cluster, which makes it flexible for managing multiple environments. An encrypted SealedSecret can be restricted so that it is decrypted only in a specific cluster and a specific namespace.

The point to watch out for in operation is private key management. If the Controller's private key is leaked, all SealedSecrets can be decrypted, so a key rotation policy and a backup strategy are essential. Also, because a SealedSecret is encrypted with the public key at the time of its creation, existing SealedSecrets must be re-encrypted after a key rotation. In large-scale environments, combining it with HashiCorp Vault or External Secrets Operator is also worth considering.

๐Ÿ’ป Code Example

Installing the Sealed Secrets Controller and using kubeseal

# Sealed Secrets Controller ์„ค์น˜ (Helm ์‚ฌ์šฉ)
helm repo add sealed-secrets https://bitnami-labs.github.io/sealed-secrets
helm repo update
helm install sealed-secrets sealed-secrets/sealed-secrets \
  --namespace kube-system \
  --set fullnameOverride=sealed-secrets-controller

# kubeseal CLI ์„ค์น˜ (macOS)
brew install kubeseal

# kubeseal CLI ์„ค์น˜ (Linux)
wget https://github.com/bitnami-labs/sealed-secrets/releases/download/v0.24.5/kubeseal-0.24.5-linux-amd64.tar.gz
tar -xvzf kubeseal-0.24.5-linux-amd64.tar.gz
sudo install -m 755 kubeseal /usr/local/bin/kubeseal

# ๊ณต๊ฐœํ‚ค ๊ฐ€์ ธ์˜ค๊ธฐ (์˜คํ”„๋ผ์ธ ์‚ฌ์šฉ ์‹œ)
kubeseal --fetch-cert \
  --controller-name=sealed-secrets-controller \
  --controller-namespace=kube-system \
  > sealed-secrets-pub.pem

Converting a Secret into a SealedSecret

# 1. ๋จผ์ € ์ผ๋ฐ˜ Secret YAML ์ƒ์„ฑ
cat > my-secret.yaml << EOF
apiVersion: v1
kind: Secret
metadata:
  name: database-credentials
  namespace: production
type: Opaque
data:
  username: YWRtaW4=  # base64 encoded: admin
  password: c3VwZXJzZWNyZXQ=  # base64 encoded: supersecret
EOF

# 2. kubeseal๋กœ ์•”ํ˜ธํ™” (ํด๋Ÿฌ์Šคํ„ฐ์— ์—ฐ๊ฒฐ๋œ ์ƒํƒœ)
kubeseal --format yaml < my-secret.yaml > sealed-secret.yaml

# 3. ๋˜๋Š” ๊ณต๊ฐœํ‚ค ํŒŒ์ผ ์ง์ ‘ ์ง€์ • (์˜คํ”„๋ผ์ธ ํ™˜๊ฒฝ)
kubeseal --format yaml \
  --cert sealed-secrets-pub.pem \
  < my-secret.yaml > sealed-secret.yaml

# 4. ์ƒ์„ฑ๋œ SealedSecret ํ™•์ธ
cat sealed-secret.yaml

SealedSecret resource example

# sealed-secret.yaml - Git์— ์•ˆ์ „ํ•˜๊ฒŒ ์ €์žฅ ๊ฐ€๋Šฅ
apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata:
  name: database-credentials
  namespace: production
spec:
  encryptedData:
    username: AgBy3i4OJSWK+PiTySYZZA9rO43cGDEq...
    password: AgBvLh7fH9/WTBu+ZqMC2nvDpAJJSzAR...
  template:
    metadata:
      name: database-credentials
      namespace: production
    type: Opaque

---
# ๋‹ค๋ฅธ ์Šค์ฝ”ํ”„ ์˜ต์…˜๋“ค
# strict (๊ธฐ๋ณธ๊ฐ’): namespace์™€ name ๋‘˜ ๋‹ค ์ผ์น˜ํ•ด์•ผ ๋ณตํ˜ธํ™”
# namespace-wide: ๊ฐ™์€ namespace ๋‚ด ์–ด๋–ค ์ด๋ฆ„์œผ๋กœ๋„ ๋ณตํ˜ธํ™” ๊ฐ€๋Šฅ
# cluster-wide: ํด๋Ÿฌ์Šคํ„ฐ ์ „์ฒด์—์„œ ๋ณตํ˜ธํ™” ๊ฐ€๋Šฅ

# namespace-wide ์Šค์ฝ”ํ”„๋กœ ์•”ํ˜ธํ™”
# kubeseal --scope namespace-wide --format yaml < my-secret.yaml

# cluster-wide ์Šค์ฝ”ํ”„๋กœ ์•”ํ˜ธํ™”
# kubeseal --scope cluster-wide --format yaml < my-secret.yaml

GitOps CI/CD pipeline example

# .github/workflows/seal-secrets.yml
name: Seal Secrets

on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Target environment'
        required: true
        type: choice
        options:
          - development
          - staging
          - production

jobs:
  seal-secret:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install kubeseal
        run: |
          wget https://github.com/bitnami-labs/sealed-secrets/releases/download/v0.24.5/kubeseal-0.24.5-linux-amd64.tar.gz
          tar -xvzf kubeseal-0.24.5-linux-amd64.tar.gz
          sudo install -m 755 kubeseal /usr/local/bin/kubeseal

      - name: Seal secrets for environment
        run: |
          CERT_FILE="certs/${{ inputs.environment }}-sealed-secrets.pem"

          # ํ™˜๊ฒฝ๋ณ„ ์‹œํฌ๋ฆฟ ์•”ํ˜ธํ™”
          for secret_file in secrets/${{ inputs.environment }}/*.yaml; do
            output_file="manifests/${{ inputs.environment }}/$(basename $secret_file .yaml)-sealed.yaml"
            kubeseal --format yaml \
              --cert "$CERT_FILE" \
              < "$secret_file" > "$output_file"
          done

      - name: Commit sealed secrets
        run: |
          git config user.name "GitHub Actions"
          git config user.email "actions@github.com"
          git add manifests/
          git commit -m "Seal secrets for ${{ inputs.environment }}"
          git push

Python script: validating and managing SealedSecrets

import subprocess
import yaml
import json
from pathlib import Path
from datetime import datetime, timedelta
from kubernetes import client, config

class SealedSecretsManager:
    def __init__(self, kubeconfig_path: str = None):
        if kubeconfig_path:
            config.load_kube_config(config_file=kubeconfig_path)
        else:
            config.load_incluster_config()

        self.custom_api = client.CustomObjectsApi()
        self.core_api = client.CoreV1Api()

    def list_sealed_secrets(self, namespace: str = None):
        """ํด๋Ÿฌ์Šคํ„ฐ์˜ ๋ชจ๋“  SealedSecret ๋ชฉ๋ก ์กฐํšŒ"""
        if namespace:
            secrets = self.custom_api.list_namespaced_custom_object(
                group="bitnami.com",
                version="v1alpha1",
                namespace=namespace,
                plural="sealedsecrets"
            )
        else:
            secrets = self.custom_api.list_cluster_custom_object(
                group="bitnami.com",
                version="v1alpha1",
                plural="sealedsecrets"
            )

        return secrets.get('items', [])

    def verify_sealed_secret(self, sealed_secret_path: str) -> bool:
        """SealedSecret์ด ํ˜„์žฌ Controller ํ‚ค๋กœ ๋ณตํ˜ธํ™” ๊ฐ€๋Šฅํ•œ์ง€ ๊ฒ€์ฆ"""
        try:
            result = subprocess.run(
                ['kubeseal', '--validate', '--format', 'yaml'],
                input=Path(sealed_secret_path).read_bytes(),
                capture_output=True
            )
            return result.returncode == 0
        except Exception as e:
            print(f"Validation failed: {e}")
            return False

    def get_controller_key_age(self, namespace: str = "kube-system"):
        """Controller์˜ ํ˜„์žฌ ํ‚ค ์ƒ์„ฑ ์‹œ์  ํ™•์ธ"""
        secrets = self.core_api.list_namespaced_secret(
            namespace=namespace,
            label_selector="sealedsecrets.bitnami.com/sealed-secrets-key=active"
        )

        if secrets.items:
            key_secret = secrets.items[0]
            creation_time = key_secret.metadata.creation_timestamp
            age = datetime.now(creation_time.tzinfo) - creation_time
            return {
                "name": key_secret.metadata.name,
                "created": creation_time.isoformat(),
                "age_days": age.days
            }
        return None

    def backup_controller_keys(self, output_dir: str):
        """Controller ํ‚ค ๋ฐฑ์—… (์žฌํ•ด๋ณต๊ตฌ์šฉ)"""
        Path(output_dir).mkdir(parents=True, exist_ok=True)

        # ๋ชจ๋“  ํ‚ค ์‹œํฌ๋ฆฟ ๋ฐฑ์—…
        secrets = self.core_api.list_namespaced_secret(
            namespace="kube-system",
            label_selector="sealedsecrets.bitnami.com/sealed-secrets-key"
        )

        for secret in secrets.items:
            backup_file = Path(output_dir) / f"{secret.metadata.name}.yaml"
            secret_dict = client.ApiClient().sanitize_for_serialization(secret)
            with open(backup_file, 'w') as f:
                yaml.dump(secret_dict, f)
            print(f"Backed up: {backup_file}")

    def rotate_and_reseal(self, manifest_dir: str, new_cert_path: str):
        """ํ‚ค ๋กœํ…Œ์ด์…˜ ํ›„ ๋ชจ๋“  SealedSecret ์žฌ์•”ํ˜ธํ™”"""
        sealed_files = list(Path(manifest_dir).rglob("*-sealed.yaml"))

        for sealed_file in sealed_files:
            # ์›๋ณธ Secret ํŒŒ์ผ ์ฐพ๊ธฐ
            original_file = str(sealed_file).replace("-sealed.yaml", ".yaml")
            if not Path(original_file).exists():
                print(f"Warning: Original secret not found for {sealed_file}")
                continue

            # ์ƒˆ ์ธ์ฆ์„œ๋กœ ์žฌ์•”ํ˜ธํ™”
            result = subprocess.run(
                ['kubeseal', '--format', 'yaml', '--cert', new_cert_path],
                input=Path(original_file).read_bytes(),
                capture_output=True
            )

            if result.returncode == 0:
                sealed_file.write_bytes(result.stdout)
                print(f"Re-sealed: {sealed_file}")
            else:
                print(f"Failed to re-seal: {sealed_file}")


# ์‚ฌ์šฉ ์˜ˆ์‹œ
if __name__ == "__main__":
    manager = SealedSecretsManager()

    # ๋ชจ๋“  SealedSecret ์กฐํšŒ
    secrets = manager.list_sealed_secrets()
    for secret in secrets:
        name = secret['metadata']['name']
        ns = secret['metadata']['namespace']
        print(f"SealedSecret: {ns}/{name}")

    # ํ‚ค ๋‚˜์ด ํ™•์ธ (30์ผ ์ด์ƒ์ด๋ฉด ๋กœํ…Œ์ด์…˜ ๊ถŒ์žฅ)
    key_info = manager.get_controller_key_age()
    if key_info and key_info['age_days'] > 30:
        print(f"Warning: Key is {key_info['age_days']} days old. Consider rotation.")

๐Ÿ—ฃ๏ธ How It's Said in Practice

  • "We're moving to GitOps and secret management is a problem, but if we adopt Sealed Secrets, we can commit secrets to Git in encrypted form."
  • "We only push SealedSecrets encrypted with kubeseal to the repo, and actual decryption is only possible inside the cluster, so it's secure."
  • "Since each environment uses a different key, they're separated so that staging's SealedSecret can't be decrypted in production."
  • "We need to decide on a Controller key rotation schedule โ€” we rotate every 30 days and run a script that automates re-encrypting the existing SealedSecrets."
  • "Please explain the difficulties of secret management in a GitOps environment and how Sealed Secrets solves them."
  • "What are the encryption mechanism of Sealed Secrets and the differences between its scopes (strict, namespace-wide, cluster-wide)?"
  • "How would you establish a key management strategy and a disaster recovery plan for the Sealed Secrets Controller?"
  • "Please compare Sealed Secrets, External Secrets Operator, and HashiCorp Vault, and explain the suitable usage scenario for each."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

  • "This Secret is only base64-encoded. Please encrypt it with Sealed Secrets and convert it into a SealedSecret."
  • "The scope is set to cluster-wide, but for security it would be better to restrict it to strict or namespace-wide."
  • "The original Secret file was committed to the repo as well. Please add it to .gitignore and delete it."
  • "After the key rotation, this SealedSecret is still encrypted with the old key. It needs to be re-encrypted."

โš ๏ธ Cautions

  • Do not expose the original Secret: The original Secret file before encryption with kubeseal must never be committed to Git. Explicitly add it to .gitignore, and make it a habit to delete it immediately after encryption. If it is committed by mistake, it must also be completely removed from the Git history.
  • Controller key backup is essential: If the Sealed Secrets Controller's private key is lost, none of the SealedSecrets can be decrypted. Back up the key regularly to a safe place (a Hardware Security Module or an encrypted backup storage), and document the disaster recovery procedure.
  • Separate keys across clusters/environments: The development, staging, and production environments must use separate Sealed Secrets Controllers and keys. Even if one environment's key is leaked, the secrets of the other environments remain safely protected. If keys are shared, environment isolation becomes meaningless.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More