How to read and write kubernetes secrets? : A practical guide (2022)
18 mins read
Founder and Engineer
Technical Content Writer
Introduction to kubernetes secrets
Kubernetes is a popular way to run containerized applications in cloud.
Often our applications require access to some sensitive data such as API Key, passwords, certificate files etc. Kubernetes offers a secure way to pass secrets to your application without needing to put those into your code or docker images.
A kubernetes secret is a object in kubernetes that contains sensitive information. Its life cycle is independent of the pods. In this tutorial, we will walk you through the different ways you can read/write kubernetes secrets.
But before that, there are a few basics to understand -
kubernetes secrets vs configmap?
Configmaps are kubernetes objects to store configuration data. Configmaps are passed to your application as environment variables, config files or application arguments.
But ConfigMaps are not recommended for storing sensitive data.
Kubernetes secrets and configmaps work very similarly. But kubernetes handles secrets in a more diligent manner than secrets. e.g. as per official docs -
A Secret is only sent to a node if a Pod on that node requires it. For mounting secrets into Pods, the kubelet stores a copy of the data into a tmpfs so that the confidential data is not written to durable storage. Once the Pod that depends on the Secret is deleted, the kubelet deletes its local copy of the confidential data from the Secret.
are kubernetes secrets secure?
As per official documentation, kubernetes secrets are stored un-encrypted form in underlying etcd server. So, anyone with API access to kubernetes cluster, can easily view the secrets. But with some additional configurations, it is possible to make secrets encrypted and secure.
Kubernetes stores your secret in base64 encoding. Base64 is not an encryption mechanism. So secrets can be easily viewed.
How to Secure Kubernetes Secrets?
To secure secrets, it's important that you -
Enable encryption at Rest: If you use a KMS key provider into your kubernetes EncryptionConfiguration, kubernetes will automatically encrypt you secrets when storing and decrypt when they are used.
RBAC control: Secrets can accessed by anyone who has permission to create pods. That is why, you can do some explicit RBAC configuration to protect your secrets.
Prerequisites for this tutorial
You need latest versions of below utilities on your system before you try this tutorial -