DEV Community

AnupamMahapatra
AnupamMahapatra

Posted on

Kubernetes Secrets

Secrets

Kubernetes Secrets let you store and manage sensitive information, such as passwords, OAuth tokens, and ssh keys. Storing confidential information in a Secret is safer and more flexible. Kubernetes uses the feature internally for generating access token for its API.

Kubernetes is managed and distributed internally. Secret can be used in the following ways:

  • Secret as environment variables
  • Secret as a file which needs a volume to be mounted with the file in it.
  • store secret as a separate image in a private registry to get pulled along with your container.

Create Secret

Generate secret from file

$ kubectl create secret generic ssh-key-secret --from-file=ssh-privatekey=/path/to/.ssh/id_rsa --from-file=ssh-publickey=/path/to/.ssh/id_rsa.pub

 secret "ssh-key-secret" created
Enter fullscreen mode Exit fullscreen mode

Generate secret using a yaml

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  username: YWRtaW4=
  password: MWYyZDFlMmU2N2Rm
Enter fullscreen mode Exit fullscreen mode

the values are Base64 values of the actual string.

$ kubectl create -f secret.yaml

secret "mysecret" created
Enter fullscreen mode Exit fullscreen mode

Using Secret

Pod using secret as env variable

apiVersion: v1
kind: Pod
metadata:
  name: secret-env-pod
spec:
  containers:
  - name: mycontainer
    image: redis
    env:
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: username
      - name: SECRET_PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: password
Enter fullscreen mode Exit fullscreen mode

Pod using secret from a volume

apiVersion: v1
kind: Pod
metadata:
  name: secret-test-pod
  labels:
    name: secret-test
spec:
  volumes:
  - name: secret-volume
    secret:
      secretName: ssh-key-secret
  containers:
  - name: ssh-test-container
    image: mySshImage
    volumeMounts:
    - name: secret-volume
      readOnly: true
      mountPath: "/etc/secret-volume"
Enter fullscreen mode Exit fullscreen mode

a volume is created of the type secret and it fetches and stores the secret from the k8 secrets. the secret is then used by the container.

here the container can now access the secret from the path

/etc/secret-volume/ssh-publickey
/etc/secret-volume/ssh-privatekey
Enter fullscreen mode Exit fullscreen mode

Demo

  • create a secret.yaml file and deploy it. Secret are now stored on k8 cluster
  • In the pod deployment use a volume that is fetching the secret and the pod must be mounting the volume to read the secret.

Top comments (0)