How to compare a value to a string with go templating

3/30/2020

I want to loop through a values file to create a namespace and a networkpolicy in/for that namespace, except for default. I only want to create the policy and not the namespace for default since it is there by default.

values file:

namespaces:
  - name: default
  - name: test1
  - name: test2

template file:

# Loop through the namespace names and create the namespaces
{{- range $namespaces := .Values.namespaces }}
{{- if ne "default" }}
apiVersion: v1
kind: Namespace
metadata:
  name: {{ $namespaces.name }}
---
{{- end }}
{{- end }}

# Loop through the namespace names and create a network policy for those namespace
{{- range $namespaces := .Values.namespaces }}                                                                                                                                                             
---                                                                                                                         
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: {{ $namespaces.name }}-networkpolicy
  namespace: {{ $namespaces.name }}
spec:
  podSelector: {}
  ingress:
    - from:
      - namespaceSelector:
          matchLabels:
            name: {{ $namespaces.name }}
---                                                                                                                         
{{- end }} 

The error I get is:

Error: UPGRADE FAILED: template: namespaces/templates/namespaces.yaml:3:7: executing "namespaces/templates/namespaces.yaml" at <ne>: wrong number of args for ne: want 2 got 1

It's probably something simple, but not seeing it. Hope someone can help.

-- bramvdk
go-templates
helmfile
kubernetes-helm

1 Answer

3/30/2020

This worked for me:

# Loop through the namespace names and create the namespaces
{{- range $namespaces := .Values.namespaces }}
{{- if ne $namespaces.name "default" }}
apiVersion: v1
kind: Namespace
metadata:
  name: {{ $namespaces.name }}
---
{{- end }}
{{- end }}

# Loop through the namespace names and create a network policy for those namespace
{{- range $namespaces := .Values.namespaces }}                                                                                                                                                             
---                                                                                                                         
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: {{ $namespaces.name }}-networkpolicy
  namespace: {{ $namespaces.name }}
spec:
  podSelector: {}
  ingress:
    - from:
      - namespaceSelector:
          matchLabels:
            name: {{ $namespaces.name }}
---                                                                                                                         
{{- end }} 
-- bramvdk
Source: StackOverflow