LIvanov
LIvanov

Reputation: 1336

Create kubernetes resources with helm only if custom resource definition exists

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?

Upvotes: 6

Views: 10502

Answers (3)

ericfossas
ericfossas

Reputation: 2196

In Helm v3, you can test for specific resources:

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

https://helm.sh/docs/chart_template_guide/builtin_objects/

Upvotes: 2

David Maze
David Maze

Reputation: 158812

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.

Upvotes: 14

Blokje5
Blokje5

Reputation: 4993

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.

Upvotes: 3

Related Questions