0
0
KubernetesHow-ToBeginner · 3 min read

How to Create Kubernetes Secret from Literal Values

Use the kubectl create secret generic command with the --from-literal flag to create a Kubernetes secret from literal values. For example, kubectl create secret generic mysecret --from-literal=username=admin --from-literal=password=pass123 creates a secret named mysecret with two keys.
📐

Syntax

The basic syntax to create a secret from literal values is:

  • kubectl create secret generic <secret-name> --from-literal=<key1>=<value1> --from-literal=<key2>=<value2>
  • <secret-name> is the name you give to the secret.
  • --from-literal adds a key-value pair directly from the command line.
  • You can add multiple --from-literal flags to include multiple keys.
bash
kubectl create secret generic mysecret --from-literal=username=admin --from-literal=password=pass123
💻

Example

This example creates a secret named db-credentials with two keys: username and password. It then shows how to view the secret metadata (not the secret data itself).

bash
kubectl create secret generic db-credentials --from-literal=username=admin --from-literal=password=secret123

kubectl get secret db-credentials -o yaml
Output
apiVersion: v1 data: password: c2VjcmV0MTIz username: YWRtaW4= kind: Secret metadata: creationTimestamp: "2024-06-01T12:00:00Z" name: db-credentials namespace: default resourceVersion: "12345" uid: 123e4567-e89b-12d3-a456-426614174000
⚠️

Common Pitfalls

  • Not encoding values: Kubernetes automatically base64 encodes secret data, so you should provide plain text literals, not base64 strings.
  • Using spaces without quotes: If your literal value contains spaces, wrap it in quotes, e.g., --from-literal="key=some value".
  • Overwriting secrets: Running the create command with the same secret name will fail; use kubectl delete secret first or use kubectl apply with a manifest.
bash
kubectl create secret generic mysecret --from-literal=password=secret 123
# This will cause an error because of the space without quotes

kubectl create secret generic mysecret --from-literal="password=secret 123"
# Correct way with quotes
📊

Quick Reference

CommandDescription
kubectl create secret generic --from-literal=key=valueCreate secret with literal key-value pairs
kubectl get secret -o yamlView secret metadata and base64 encoded data
kubectl delete secret Delete existing secret
Use quotes around values with spacesAvoid syntax errors when literals contain spaces

Key Takeaways

Use kubectl create secret generic with --from-literal to create secrets from plain text values.
Multiple --from-literal flags can add multiple key-value pairs in one command.
Wrap literal values in quotes if they contain spaces to avoid errors.
Kubernetes automatically base64 encodes secret data; provide plain text literals.
To update a secret, delete it first or use a manifest with kubectl apply.