How to handle Secrets in a Spring Boot Application while deploying to Kubernetes
Let’s say you have a Spring Boot Application with Secrets in the application.yml file.
cloudinary:
cloud-name: cloud-name-value
api-key: api-key-value
api-secret: api-secret-value
We don’t want to commit our projects as is it currently, since Committing Secrets is a No-Go, we need to find a way to put the values in the application.yml file before Deployment.
The solution is to use the Secret Object in Kubernetes to create environment variables. Then we will use placeholders in our application.yml file to refer to those environment variables.
Such that, the application.yml becomes:
cloudinary:
cloud-name: ${CLOUDINARY_CLOUD_NAME:``}
api-key: ${CLOUDINARY_API_KEY:``}
api-secret: ${CLOUDINARY_API_SECRET:``}
and we need to create a Kubernetes Secret Object cloudinary-credentials:
kubectl create secret generic cloudinary-credentials --from-literal=CLOUDINARY_CLOUD_NAME=cloud-name-value --from-literal=CLOUDINARY_API_KEY=api-key-value --from-literal=CLOUDINARY_API_SECRET=api-secret-value
Then we need to create our environment variables from this new Secret Object in our deployment definition like so:
apiVersion: apps/v1
kind: Deployment
metadata:
name: #APP#
namespace: #NAMESPACE#
spec:
selector:
matchLabels:
app: #APP#
replicas: 1
template:
metadata:
labels:
app: #APP#
spec:
containers:
- image: #IMAGE#
name: #APP#
imagePullPolicy: Always
ports:
- containerPort: 8080
envFrom:
- secretRef:
name: cloudinary-credentials
With this, we have successfully avoided committing our credentials, or building them with the jar file.
Happy Coding :)