Updated on 2023-07-06 GMT+08:00

Secret

A secret is a resource object that is encrypted for storing the authentication information, certificates, and private keys. The sensitive data will not be exposed in images or pod definitions, which is safer and more flexible.

Similar to a ConfigMap, a secret stores data in key-value pairs. The difference is that a secret is encrypted, and is suitable for storing sensitive information.

Base64 Encoding

A secret stores data in key-value pairs, the same form as that of a ConfigMap. The difference is that the value must be encoded using Base64 when a secret is created.

To encode a character string using Base64, run the echo -n to-be-encoded content | base64 command. The following is an example:

root@ubuntu:~# echo -n "3306" | base64
MzMwNg==

Creating a Secret

The secret defined in the following example contains two key-value pairs.

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
data:
  key1: aGVsbG8gd29ybGQ=   # hello world, a value encoded using Base64
  key2: MzMwNg==           # 3306, a value encoded using Base64

Referencing a Secret as an Environment Variable

Secrets are usually injected into containers as environment variables, as shown in the following example.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx:alpine
    name: container-0
    resources:
      limits:
        cpu: 100m
        memory: 200Mi
      requests:
        cpu: 100m
        memory: 200Mi
    env:
    - name: key
      valueFrom:
        secretKeyRef:
          name: mysecret
          key: key1
  imagePullSecrets:
  - name: default-secret

Referencing a Secret in a Volume

Referencing a secret in a volume is to fill its data in configuration files in the volume. Each piece of data is saved in a file. The key is the file name, and the key value is the file content.

In the following example, create a volume named vol-secret, reference the secret named mysecret in the volume, and mount the volume to the /tmp directory of the container. After the pod is created, the two files key1 and key2 are generated in the /tmp directory of the container.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx:alpine
    name: container-0
    resources:
      limits:
        cpu: 100m
        memory: 200Mi
      requests:
        cpu: 100m
        memory: 200Mi
    volumeMounts:
    - name: vol-secret              # Mount the volume named vol-secret.
      mountPath: "/tmp"
  imagePullSecrets:
  - name: default-secret
  volumes:
  - name: vol-secret
    secret:                         # Reference the secret.
      secretName: mysecret

In the pod container, you can find the two files key1 and key2 in the /tmp directory. The values in the files are the values encoded using Base64, which are hello world and 3306.