Secret solves the configuration problem of sensitive data, such as passwords, tokens, and keys, without exposing these sensitive data to the image or Pod Spec. Secret can be used as a Volume or environment variable

Secret comes in three types:

  • Service Account: Used to access the Kubernetes API, which is automatically created by Kubernetes and automatically mounted to Pod/run/secrets/kubernetes.io/serviceaccountIn the directory
  • Opaque: Secret in base64 encoding format, used to store passwords and keys
  • Kubernetes. IO/dockerconfigjson: used to store the private docker registry authentication information

Service Account

Service the Account used to access Kubernetes API, Kubernetes automatically created, and will automatically be mounted to the Pod/run/secrets/Kubernetes IO/serviceaccount directory

$ kubectl run nginx --image nginx
deployment "nginx" created
$ kubectl get pods.$ kubectl exec nginx-xxx ls /run/secrets/kubernetes.io/serviceaccount
ca.crt
namespace
token
Copy the code

Opaque Secret

1. Creation instructions

$ echo -n "admin" | base64
YWRtaW4=
$ echo -n "1f2d1e2e67df" | base64
MWYyZDFlMmU2N2Rm
Copy the code

secrets.yaml

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: MWYyZDFlMmU2N2Rm
  username: YWRtaW4=
Copy the code

2. Usage

2.1 Mounting Secret to the Volume

apiVersion: v1
kind: Pod
metadata:
  labels:
    name: secret-test
  name: secret-test
spec:
  volumes:
  - name: secrets
    secret:
      secretName: mysecret
  containers:
  - image: myapp:v1
    name: db
    volumeMounts:
    - name: secrets
      mountPath: "/etc/secrets"
      readOnly: true
Copy the code

2.2 Importing Secret into environment variables

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: pod-deployment
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: pod-deployment
    spec:
      containers:
      - name: pod-1
        image: myapp:v1
        ports:
        - containerPort: 80
        env:
        - name: TEST_USER
          valueFrom:
            secretKeyRef:
              name: mysecret
              key: username
        - name: TEST_PASSWORD
          valueFrom:
            secreKeyRef:
              name: mysecret
              key: password
Copy the code

Kubernetes.io/dockerconfigjson

Create a Docker Registry certified secret using Kubectl

$ kubectl create docker-registry myregistrykey --docker-server=hub.example.com --docker-username=admin --docker-password=Harbor12345 [email protected]
Copy the code

When creating a Pod, reference the newly created MyRegistryKey via imagePullSecrets

apiVersion: v1
kind: Pod
metadata:
  name: foo
spec:
  containers:
    - name: foo
      image: wst/example:v1 # mirroring in a private repository
  imagePullSecrets:
    - name: myregistrykey
Copy the code