Interview Prep/Helm/Templating: Go Templates & Sprig

How can a template check whether an API version exists in the cluster?

IntermediateConceptTemplating: Go Templates & Sprig
Answer
{{- if .Capabilities.APIVersions.Has "autoscaling/v2" }}
apiVersion: autoscaling/v2
{{- else }}
apiVersion: autoscaling/v2beta2
{{- end }}
kind: HorizontalPodAutoscaler

You can test a specific kind too: .Capabilities.APIVersions.Has "monitoring.coreos.com/v1/ServiceMonitor". Remember that helm template uses defaults unless you pass --api-versions, so CI renders should set it to match the target cluster.

All Helm questions Roadmap: Helm

More on Templating: Go Templates & Sprig