How to Create Secret in Kubernetes: Simple Guide
To create a secret in Kubernetes, use the
kubectl create secret command with the secret type and data, or define it in a YAML file and apply it with kubectl apply -f. Secrets store sensitive data like passwords securely inside your cluster.Syntax
The basic syntax to create a secret using kubectl is:
kubectl create secret <type> <name> [--from-literal=key=value] [--from-file=path]kubectl apply -f <secret.yaml>to create from a YAML file
Here, <type> can be generic, docker-registry, or tls. The --from-literal adds key-value pairs directly, and --from-file adds data from files.
bash
kubectl create secret generic my-secret --from-literal=username=admin --from-literal=password=secret123 # Or create from YAML file kubectl apply -f secret.yaml
Example
This example creates a generic secret named my-secret with username and password, then shows how to create the same secret using a YAML file.
bash
kubectl create secret generic my-secret --from-literal=username=admin --from-literal=password=secret123 # YAML file content (secret.yaml): apiVersion: v1 kind: Secret metadata: name: my-secret type: Opaque data: username: YWRtaW4= # base64 for 'admin' password: c2VjcmV0MTIz # base64 for 'secret123' # Apply the YAML kubectl apply -f secret.yaml
Output
secret/my-secret created
secret/my-secret configured
Common Pitfalls
Common mistakes when creating secrets include:
- Not encoding data in base64 when using YAML files (Kubernetes requires base64 encoded values).
- Using
kubectl create secretwith files that contain extra spaces or newlines, which can cause unexpected data. - Exposing secrets in plain text in YAML files or command history.
Always verify secret data with kubectl get secret <name> -o yaml and avoid committing secrets to public repositories.
yaml
## Wrong: plain text in YAML (will cause error or wrong data) apiVersion: v1 kind: Secret metadata: name: bad-secret data: password: secret123 ## Right: base64 encoded value apiVersion: v1 kind: Secret metadata: name: good-secret data: password: c2VjcmV0MTIz
Quick Reference
| Command or Field | Description |
|---|---|
| kubectl create secret generic | Create secret with key-value pairs |
| kubectl create secret generic | Create secret from file content |
| kubectl apply -f secret.yaml | Create secret from YAML file |
| type: Opaque | Default secret type for generic secrets |
| data: | Base64 encoded key-value pairs in YAML |
| stringData: | Plain text key-value pairs in YAML (Kubernetes encodes automatically) |
Key Takeaways
Use kubectl create secret with --from-literal or --from-file to create secrets quickly.
When using YAML, encode secret data in base64 under the data field or use stringData for plain text.
Avoid exposing secrets in plain text or committing them to version control.
Verify secrets with kubectl get secret -o yaml to check stored data.
Use the secret type 'generic' for most cases unless you need docker-registry or tls types.