How to Create a Secret in Kubernetes


Secrets allow applications to not hardcode usernames, passwords or additional information such as hostnames, IP addresses or other protected/sensitive information.

Create a Secret in Kubernetes

It’s simple to create a secret in Kubernetes . It can either be done --from-file or --from-literal.

Option 1: From a File

echo -n 'adminuser' > ./username.txt
echo -n 'jf392hf782hf932h' > ./password.txt

kubectl create secret generic admin-user-pass \
  --from-file=./username.txt \
  --from-file=./password.txt

The result will be something like:

secret/admin-user-pass created

By default, the key name is the filename, but we could also be explicit about this:

kubectl create secret generic admin-user-pass \
  --from-file=username=./username.txt \
  --from-file=password=./password.txt

Option 2: From a Literal

We don’t have to create a file to create a secret, we can also create one on the fly:

kubectl create secret generic admin-user-pass \
  --from-literal=username=adminuser \
  --from-literal=password='jf392hf782hf932h'

The result will be something like:

secret/admin-user-pass created