[Helm] How to check semantic version in helm chart

Helm chart supports the semantic veresion check function. We can find it here

1. Compare semantic version string

It is very helpful for some cases. For example, if the helm chart needs to decide the probe port based on the docker image version.

Let’s say that a web service started to support HTTPs feature since version 22.5.0, so if the installed docker image is after 22.5.0, the default probe port should be 8443. Otherwise, the default probe port will be 8000

In helm chart, we can achieve this with

 1livenessProbe:
 2  httpGet:
 3    path: /
 4    {{- if eq (semver .Values.image.tag | (semver "22.5.0").Compare) -1 }}
 5    port: 8443
 6    scheme: HTTPS
 7    {{- else }}
 8    port: 8000
 9    scheme: HTTP  
10    {{- end }}  

When semver .Values.image.tag | (semver "22.5.0").Compare == -1, it means that the version of .Values.image.tag is after 22.5.0.
Similarly, {{- if eq (semver .Values.image.tag | (semver "22.5.0").Compare) 1 }} means that the version of .Values.image.tag is before 22.5.0

2. Check if a string is semantic version string

Apart from comparison of semantic version string, sometimes we may need to decide if a value is a semantic string. For example, it is very common that docker image has latest tag which is not the semantic version string. If we don’t check the value first, helm chart install will report the below error when .Values.image.tag is latest:

Error: template: xx/templates/deployment.yaml:98:34: executing "xx/templates/deployment.yaml" at <semver .Values.image.tag>: error calling semver: Invalid Semantic Version

The solution is as below

 1livenessProbe:
 2  httpGet:
 3    path: /
 4    {{- if regexMatch "^[0-9]+\\.[0-9]+\\.[0-9]+$" .Values.image.tag }}
 5      {{- if eq (semver .Values.image.tag | (semver "22.5.0").Compare) -1 }}
 6    port: 8443
 7    scheme: HTTPS
 8      {{- else }}
 9    port: 8000
10    scheme: HTTP
11      {{- end }}
12    {{- else }}
13    port: 8443
14    scheme: HTTPS
15    {{- end }}

Yes. With another helm chart supported function regexMatch, we can achive the goal. If the semantic version is not only composed of major.minor.patch, we just need to adjust the regular expression. It is pretty straightforward.


If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!
Buy Me A Coffee
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !