Kubernetes includes a secret resource store.
We can get a list of secrets via the namespace
kubectl get secrets -n dev
and for all namespaces using
kubectl get secrets --all-namespaces
We can create a secret of the specified type
- docker-registry Create a secret for use with a container registry
- generic Create a secret from a local file, directory, or literal value, known as an Opaque secret type
- tls Create a TLS secret, such as a TLS certificate and its associated key
Hence we use the “specified type” as below (which uses a generic type)
kubectl create secret generic my-secret \ --from-literal=username=admin \ --from-literal=password=secret123 \ -n dev
With the above command, we created a secret with the name my-secret and the key username with value admin followed by another key/value.
A secret can be created using Kubernetes YAML file with kind “Secret”
apiVersion: v1 kind: Secret metadata: name: my-secret type: Opaque data: username: YWRtaW4= # base64 encoded 'admin' password: c2VjcmV0MTIz # base64 encoded 'secret123'
Accessing secrets, we can use the following
kubectl get secret my-secret -o jsonpath="{.data.username}" -n dev | base64 --decode
kubectl get secret my-secret -o jsonpath="{.data.username}" -n dev
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YWRtaW4=")) // insert string from the above
Or using Powershell
$encoded = kubectl get secret my-secret -o jsonpath="{.data.username}" -n dev
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($encoded))
Here’s an example using a secret by including them in environment varianles
env:
- name: DB_USER
valueFrom:
secretKeyRef:
name: my-secret
key: username
this gives us process.env.DB_USER.
Another use is mounting via the pods volume, hence it’s file system
volumes:
- name: secret-volume
secret:
secretName: my-secret
volumeMounts:
- name: secret-volume
mountPath: "/etc/secret"
readOnly: true