Creating, Developing, and Testing a Helm Chart
Adding a Secret for Image Pulling
Since our Docker image is hosted in a private Harbor registry, we need to create a Docker registry secret and link it to the ServiceAccount used by our application Pods.
ℹ️ We create a dedicated ServiceAccount because Kubernetes only uses registry credentials via ServiceAccounts. By attaching our Harbor pull secret to the ServiceAccount and using it in the Deployment, we ensure our Pods can authenticate to the private registry securely and reliably.
As a reminder, the Docker registry secret has the following format:
{
"auths": {
"" : {
"username": "" ,
"password": "" ,
"auth": ""
}
}
}
The whole secret is then base64-encoded and stored in a Kubernetes Secret of type kubernetes.io/dockerconfigjson. This is what we need to add to our chart:
cat < $HOME/todo-chart/templates/registry-secret.yaml
{{- if .Values.imageCredentials.create }}
apiVersion: v1
kind: Secret
metadata:
name: {{ .Values.imageCredentials.secretName }}
labels:
{{- include "todo-chart.labels" . | nindent 4 }}
type: kubernetes.io/dockerconfigjson
data:
.dockerconfigjson: {{ template "todo-chart.dockerconfigjson" . }}
{{- end }}
EOF
The above template will create a Secret only if the imageCredentials.create value is set to true in the values.yaml file. The name of the Secret is defined by the imageCredentials.secretName value. The .dockerconfigjson field is populated using a Helm template function called todo-chart.dockerconfigjson, which we need to define in the _helpers.tpl file:
cat <<'EOT' >> $HOME/todo-chart/templates/_helpers.tpl
{{/*
This helper builds the value for `.dockerconfigjson` in a Secret of type
`kubernetes.io/dockerconfigjson`. Helm templates it using the values:
- .Values.imageCredentials.registry (e.g. "harbor.example.com" or "IP:30003")
- .Values.imageCredentials.username (registry username)
- .Values.imageCredentials.password (registry password)
It returns a *base64-encoded* docker config JSON document, as required
by Kubernetes for this secret type.
*/}}
{{- define "todo-chart.dockerconfigjson" -}}
{{- /*
Step 1: Build auth = base64("username:password")
*/ -}}
{{- $auth := printf "%s:%s" .Values.imageCredentials.username .Values.imageCredentials.password | b64enc }}
{{- /*
Step 2: Build the docker config JSON structure and base64-encode it.
*/ -}}
{{- printf "{\"auths\":{\"%s\":{\"username\":\"%s\",\"password\":\"%s\",\"auth\":\"%s\"}}}" .Values.imageCredentials.registry .Values.imageCredentials.username .Helm in Practice
Designing, Deploying, and Operating Kubernetes Applications at ScaleEnroll now to unlock current content and receive all future updates for free. Your purchase supports the author and fuels the creation of more exciting content. Act fast, as the price will rise as the course nears completion!
Hurry! This limited time offer ends in:
To redeem this offer, copy the coupon code below and apply it at checkout:
