Search code examples
kubernetesgoogle-kubernetes-enginekubernetes-helm

Helm lookup always empty


While deploying a Kubernetes application, I want to check if a resource is already present. If so it shall not be rendered. To archive this behaviour the lookup function of helm is used. As it seems is always empty while deploying (no dry-run). Any ideas what I am doing wrong?

    ---
{{- if not (lookup "v1" "ServiceAccount" "my-namespace" "my-sa") }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ .Chart.Name }}-{{ .Values.environment }}
  namespace: {{ .Values.namespace }}
  labels: 
    app:  {{ $.Chart.Name }}
    environment: {{ .Values.environment }}
  annotations:
    "helm.sh/resource-policy": keep
    iam.gke.io/gcp-service-account: "{{ .Chart.Name }}-{{ .Values.environment }}@{{ .Values.gcpProjectId }}.iam.gserviceaccount.com"
{{- end }}

running the corresponding kubectl command return the expected service account

kubectl get ServiceAccount my-sa -n my-namespace lists the expected service account

helm version: 3.5.4


Solution

  • i think you cannot use this if-statement to validate what you want.

    the lookup function returns a list of objects that were found by your lookup. so, if you want to validate that there are no serviceaccounts with the properties you specified, you should check if the returned list is empty.

    test something like

    ---
    {{ if eq (len (lookup "v1" "ServiceAccount" "my-namespace" "my-sa")) 0 }}
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: {{ .Chart.Name }}-{{ .Values.environment }}
      namespace: {{ .Values.namespace }}
      labels: 
        app:  {{ $.Chart.Name }}
        environment: {{ .Values.environment }}
      annotations:
        "helm.sh/resource-policy": keep
        iam.gke.io/gcp-service-account: "{{ .Chart.Name }}-{{ .Values.environment }}@{{ .Values.gcpProjectId }}.iam.gserviceaccount.com"
    {{- end }}
    

    see: https://helm.sh/docs/chart_template_guide/functions_and_pipelines/#using-the-lookup-function