Creating Secrets from Files
What you'll learn: How to generate Kubernetes Secrets directly from existing files containing sensitive data like certificates, keys, or credential files.
The Core Idea
While creating Secrets from literal values works well for simple key-value pairs, real-world sensitive data often lives in files—think SSH keys, TLS certificates, JSON service account credentials, or configuration files with passwords. Kubernetes allows you to create Secrets directly from these files using kubectl, which reads the file contents and stores them as base64-encoded data.
Think of it like this: Instead of typing your credit card number into a form field, you're uploading a scan of the card. The file itself becomes the Secret's value, preserving formatting, line breaks, and binary data exactly as-is.
How It Works
Use kubectl create secret generic with the --from-file flag:
kubectl create secret generic db-creds --from-file=./database.conf
This command:
- Creates a Secret named
db-creds - Reads the contents of
database.conf - Stores it with the key
database.conf(the filename becomes the key by default)
Custom key names: You can specify your own key:
kubectl create secret generic tls-cert --from-file=tls.crt=./server.crt
Now the certificate data is stored under the key tls.crt instead of server.crt.
Multiple files: Load several files into one Secret:
kubectl create secret generic app-creds \
--from-file=username.txt \
--from-file=password.txt
When to Use This
Perfect for certificates, private keys, credential files, or any sensitive data already stored in files. It preserves the exact file structure your applications expect.
Key Takeaway: Creating Secrets from files lets you import existing sensitive files directly into Kubernetes, with filenames becoming Secret keys and contents automatically base64-encoded for secure storage.