Customize apiVersion in helm templates


Context

When deploying a helm chart (or a Kubernetes manifest) to different Kubernetes clusters, sometimes you may run into a situation where a resource’s apiVersion is no longer accepted by the Kubernetes API. This usually happens when the deprecation period for the API has completed.

In my case, we ran into this issue with the Ingress resource apiVersion, which in version 1.22 stopped serving extensions/v1beta1 and networking.k8s.io/v1beta1 API versions.

Implementation

In particular with Helm, we can dynamically set the Ingress apiVersion based on the Kubernetes version where the chart is deployed by using the following functionality:

  • semverCompare: a comparison function which allows comparing SemVer versions (including support for ranges)
  • Capabilities : an object available for templates in the chart.

Using the above, the apiVersion block definition would look like:

{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
... # Rest of the ingress resource definition

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.