What are K8s Secrets and how does it work?
Secrets are Kubernetes object that is one of the container orchestration platform’s built-in security capabilities. In general, a secret has sensitive information that is secured. Similarly, a “secret” in Kubernetes is a means of storing sensitive information, like usernames, passwords, tokens, OAuth token, or SSH key, so that it’s accessible when necessary to pods in your cluster but protected from unnecessary visibility that could create security risks.
When creating a Pod, Kubernetes automatically creates a service account Secret and automatically modifies your Pod to use this Secret. The service account token Secret contains credentials for accessing the API. The automatic creation and use of API credentials can be disabled or overridden if desired.
The big benefit of K8s Secrets:
The main benefit of Kubernetes secrets is to decouple secrets from the application code and help reuse them whenever needed inside the cluster. Secrets help organize and distribute sensitive information across a cluster. It also prevents accidental exposure of the information stored in it while at the same time making it available wherever the user needs it.
Individual secrets are limited to 1MiB in size. This is to discourage the creation of very large secrets which would exhaust the API server and kubelet memory. However, creation of many smaller secrets could also exhaust memory.
How to create a secret
Secret are of 3 types
- Docker Registry
For this tutorial, we will use the generic type of secret
Creating secrets using literals
kubectl create secret generic first --from-literal=name=gaurav
using the above commands we can create a secret using literal and kubectl and later can use this secret in our pods
Note: when we will describe the secret then we will not be able to see its value as it will be in a base64 encoded format
Creating secrets using file
kubectl create secret generic --from-file=devapplication.properties
the above command will create the secret of the above property file and that will be in the bash64 format. This recently created secret then we can use in our pod creation yaml
Creating secrets using env file
variable1=value1 variable2=value2 variable3=value3 variable4=value4
kubectl create secret generic fromenvfile --from-env-file=env.sh
the above file will create the env variable in the secret and the env variables we can use inside the pods
Note: always keep encrypted value in YAML file, convert the value in base64 format first before putting it into YAML file