0
0
KubernetesHow-ToBeginner · 3 min read

How to Encode and Decode Secrets in Kubernetes

In Kubernetes, secrets must be encoded in base64 before storing them in YAML files or manifests. To decode a secret, use the base64 --decode command or Kubernetes commands like kubectl get secret with output formatting.
📐

Syntax

To encode a secret value, use the base64 command. To decode, use base64 --decode. Kubernetes stores secrets in base64 format inside YAML manifests.

  • echo -n 'your-secret' | base64: Encodes the secret string.
  • echo 'encoded-string' | base64 --decode: Decodes the base64 string back to original.
  • kubectl get secret your-secret -o yaml: Shows the secret in base64 encoded form.
bash
echo -n 'myPassword123' | base64
# Output: bXlQYXNzd29yZDEyMw==
echo 'bXlQYXNzd29yZDEyMw==' | base64 --decode
# Output: myPassword123
Output
bXlQYXNzd29yZDEyMw== myPassword123
💻

Example

This example shows how to create a Kubernetes secret with an encoded password and then decode it from the cluster.

bash
PASSWORD=myPassword123
ENCODED_PASSWORD=$(echo -n "$PASSWORD" | base64)

cat <<EOF > secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: $ENCODED_PASSWORD
EOF

kubectl apply -f secret.yaml

kubectl get secret mysecret -o jsonpath='{.data.password}' | base64 --decode
Output
myPassword123
⚠️

Common Pitfalls

Common mistakes include:

  • Encoding secrets with a trailing newline by using echo without -n, which changes the secret value.
  • Trying to store plain text secrets directly in YAML without encoding, causing errors.
  • Decoding secrets incorrectly by not using base64 decode or misreading the output.
bash
echo 'myPassword123' | base64
# Wrong: adds newline, encoded value differs

echo -n 'myPassword123' | base64
# Correct: no newline, exact encoding
📊

Quick Reference

ActionCommand ExampleDescription
Encode secretecho -n 'secret' | base64Convert plain text to base64 for Kubernetes
Decode secretecho 'encoded' | base64 --decodeConvert base64 back to plain text
Create secret YAMLkubectl create secret generic name --from-literal=key=secretCreate secret directly from literal
View secretkubectl get secret name -o yamlShow secret in base64 format
Decode secret from clusterkubectl get secret name -o jsonpath='{.data.key}' | base64 --decodeRetrieve and decode secret value

Key Takeaways

Always encode secrets in base64 before storing in Kubernetes manifests.
Use echo with -n to avoid adding unwanted newlines during encoding.
Decode secrets using base64 --decode or kubectl commands to retrieve original values.
Kubernetes stores secrets in base64 format, not encrypted by default.
Use kubectl commands to manage and verify secrets safely.