I want tmp/my_secret.txt
in my container running in kubernetes cluster.
I deploy using helm chart. My chart directory is helms/my_chart
.
secret.yaml
Create secret.yaml
in helms/my_chart/templates
directory:
apiVersion: v1
kind: Secret
metadata:
# secret name in kubernetes
name: k8s-secret
namespace: my-app
data:
# key is filename
# value is the content of the file in base64
"my_secret.txt": {{.Values.my_secret_base64}}
deployment.yaml
Make sure setting in helms/my_chart/deployment.yaml
’s volume
and volumeMounts
are defined as follow (This is default deployment.yaml
generated by helm create
)
apiVersion: apps/v1
kind: Deployment
metadata:
...
spec:
...
template:
metadata:
...
spec:
...
containers:
- name: {{ .Chart.Name }}
...
{{- with .Values.volumeMounts }}
volumeMounts:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.volumes }}
volumes:
{{- toYaml . | nindent 8 }}
{{- end }}
...
values.yaml
volume
and volumeMounts
settings in values.yaml
are:
volumes:
# volume name to be referenced at volumeMounts
- name: my-secret-vol
secret:
# name of k8s secret
secretName: k8s-secret
optional: false
volumeMounts:
# volume's name
- name: my-secret-vol
# path to map to, WORKDIR is /app
mountPath: "/app/tmp"
readOnly: true
Directory
.
├── helms
│ └── my_chart
│ ├── Chart.yaml
│ ├── charts
│ └── templates
│ ├── NOTES.txt
│ ├── ...
│ ├── deployment.yaml
│ └── secret.yaml
├── tmp
│ ├── my_secret.txt
│ └── my_secret_b64.txt
└── values.yaml
Deploy helm
# Prepare the secret
#####################
# do necessary to get my_secret.txt from secret manager / vault to tmp/my_secret.txt
# for example
cat tmp/my_secret.txt
# world peace
# create a base64 version
# -w0 is to have
base64 -w0 tmp/my_secret.txt > tmp/my_secret_base64.txt
cat tmp/my_secret_base64.txt
#d29ybGQgcGVhY2U=
# do helm stuff
# use --set-file to set the value for my_secret_base64 in secret.yaml
helm upgrade --install --create-namespace \
--namespace my_app \
--set-file my_secret_base64=tmp/my_secret_base64.txt \
-f values.yaml \
my_app_release "./helms/my_chart"
Verify
# check the secret
# --template={{.data.key}} does not work for key with dot
kubectl get secret -n my_app \
k8s-secret -o jsonpath="{.data.my_secret\.text}" \
| base64 -d
# world peace
# check in container
kubectl exec -it my_app_pod12345 -- bash
ls /app/tmp
# my_secret.txt
cat /app/tmp/my_secret.txt
# world peace
— The End, enjoy! —