Create kubernetes resources with helm only if custom resource definition exists

12/17/2019

I have a helm chart that deploys a number of Kubernetes resources. One of them is a resource that is of a Custom Resource Definition (CRD) type (ServiceMonitor used by prometheus-operator).

I am looking for a way, how to "tell" helm that I'd want to create this resource only if such a CRD is defined in the cluster OR to ignore errors only caused by the fact that such a CRD is missing.

Is that possible and how can I achieve that?

-- LIvanov
kubernetes
kubernetes-helm

2 Answers

12/17/2019

Helm's Capabilities object can tell you if an entire API class is installed in the cluster. I don't think it can test for a specific custom resource type.

In your .tpl files, you can wrap the entire file in a {{ if }}...{{ end }} block. Helm doesn't especially care if the rendered version of a file is empty.

That would lead you to a file like:

{{ if .Capabilities.APIVersions.Has "monitoring.coreos.com/v1" -}}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  ...
{{ end -}}

That would get installed if the operator is installed in the cluster, and skipped if not.

-- David Maze
Source: StackOverflow

12/17/2019

If you are on Helm 3 you can put your CRD in the crds/ directory. Helm will treat it differently, see the docs here.

In Helm 2 there is another mechanism using the crd-install hook. You can add the following to your CRD:

annotations:
  "helm.sh/hook": crd-install

There are some limitations with this approach so if you are using Helm 3 that would be preferred.

-- Blokje5
Source: StackOverflow