Kubernetes - How to use Secrets Kind Resources

Kubernetes - How to use Secrets Kind Resources

Working with Kubernetes Secrets

Kubernetes provide facility to developer to store sensitive data like configuration, settings, username and password in secret way. This can be achieved by declaring Secret kind resource in Kubernetes.

Declaring secret resource:

For example, herein, we are declaring secret resource with name mysecret and storing data in this secret with keys username and password.

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

 

Reading secrets in Kubernetes : 

You need to just treat secrets like storage directory having file. So, need to mount this storage just persistence storage and then you can read secrets data.  Here we are mounting mysecret with volume name mysecret -volume. And then you can mount this volume to your container at your desired mount path. Here, you are mounting volume mysecret -volume at the path “/etc/my-secret-data”. Then you can read data from this location inside of this container (e.g. httpd in this case).

apiVersion: v1
kind: Pod
metadata:
  name: my-httpd-1
  labels:
    app: my-httpd-1
spec:
  volumes:
    # create secrets volume here, each key will behave like file
    - name: mysecret-volume
      secret:
        secretName: mysecret
  containers:
    - name: httpd
      image: phpstorm/php-73-apache-xdebug-27
      ports:
        - containerPort: 80
      volumeMounts:
        - name: mysecret-volume
          mountPath: "/etc/my-secret-data"

Here is the example to read secrets. Reading secretes using PHP code:

$file=fopen("/etc/my-secret-data/username","r");
echo fread($file,filesize("/etc/my-secret-data/username"));
fclose($file);

 

Tags