- Building Google Cloud Platform Solutions
- Ted Hunter Steven Porter Legorie Rajan PS
- 343字
- 2025-04-04 14:47:42
Using secrets
Secrets can be accessed from your clusters by two mechanisms: through a mounted volume or through set environment variables. Exposing secrets to your cluster workloads occurs at deployment time by declaring either volumes or environment variables that reference your secrets.
This is an updated version of our basic deployment YAML file that now includes a configuration definition for a mounted volume referencing our creds secret:
---
apiVersion: "extensions/v1beta1"
kind: "Deployment"
metadata:
name: "nginx-1"
namespace: "default"
labels:
app: "nginx-1"
spec:
replicas: 3
selector:
matchLabels:
app: "nginx-1"
template:
metadata:
labels:
app: "nginx-1"
spec:
containers:
- name: "nginx"
image: "nginx:latest"
env:
- name: creds-username
valueFrom:
secretKeyRef:
name: creds
key: username
- name: creds-password
valueFrom:
secretKeyRef:
name: creds
key: password
volumes:
- name: creds-volume
secret:
secretName: creds
---
apiVersion: "autoscaling/v1"
kind: "HorizontalPodAutoscaler"
metadata:
name: "nginx-1-hpa"
namespace: "default"
labels:
app: "nginx-1"
spec:
scaleTargetRef:
kind: "Deployment"
name: "nginx-1"
apiVersion: "apps/v1beta1"
minReplicas: 1
maxReplicas: 5
targetCPUUtilizationPercentage: 80
You can also update the same YAML configuration file to include environment variable definitions referencing our creds secret:
---
apiVersion: "extensions/v1beta1"
kind: "Deployment"
metadata:
name: "nginx-1"
namespace: "default"
labels:
app: "nginx-1"
spec:
replicas: 3
selector:
matchLabels:
app: "nginx-1"
template:
metadata:
labels:
app: "nginx-1"
spec:
containers:
- name: "nginx"
image: "nginx:latest"
volumeMounts:
- name: creds-volume
mountPath: /etc/creds-volume
volumes:
- name: creds-volume
secret:
secretName: creds
---
apiVersion: "autoscaling/v1"
kind: "HorizontalPodAutoscaler"
metadata:
name: "nginx-1-hpa"
namespace: "default"
labels:
app: "nginx-1"
spec:
scaleTargetRef:
kind: "Deployment"
name: "nginx-1"
apiVersion: "apps/v1beta1"
minReplicas: 1
maxReplicas: 5
targetCPUUtilizationPercentage: 80
More advanced scenarios exist that only apply to secrets created as mounted volumes. Some of the more advanced capabilities for consuming secrets include:
- Specifying a mount path where a secret mounted volume will be exposed
- Specifying the path within a value where individual keys are projected
- Specifying file permissions for volume-mounted secrets
Once you have secrets exposed within your GKE container cluster, using them from your applications or services is no different than referencing a normal file or set of environment variables.
Here, we are reading a secret exposed via environment variables:
$ echo $creds-username
Here, we are reading a secret exposed via a mounted volume:
$ cat /etc/creds-volume/username