i want to pre-populate a kubernetes cluster with namespaces and their respective secrets for our apps and services.
For that i would like to be able to specify 2 lists, 1 list with secrets, and 1 list with namespaces. Each namespace in the list has a list of secrets.
Like this values.yaml:
secrets:
- name: secret1
data: key1
- name: secret2
data: key2
- name: secret3
data: key3
namespaces:
- name: app1
secrets:
- secret1
- secret2
- name: app2
secrets:
- secret1
- secret3
Then i want to loop over namespaces to create the namespaces, like:
{{- range $namespaces := .Values.namespaces }}
apiVersion: v1
kind: Namespace
metadata:
name: {{ $namespaces.name }}
---
{{- end }}
In that loop i want another loop inside this loop that creates the secrets per namespace with the data from the secrets list. A bit like this:
{{- range $secrets := .secrets }}
apiVersion: v1
kind: Secret
metadata:
name: {{ .name }}
namespace: {{ $namespaces.name }}
type: kubernetes.io/tls
data: $secrets.data
---
{{- end }}
But if i put that loop inside the namespace loop, it just creates all secrets in the secrets list in all namespaces.
How can i make the loop only create the secrets specified in the namespaces list?
I think it can be done with the go template index function, but i don't know how.
Best Answer
I have made reproduction on your problem and find answer for that.
Your example
I used your yamls to create namespaces and changed the second one so it's actually work now.
values.yaml
templates/namespaces.yaml
Result:
My idea of doing that
Instead of creating secrets for namespaces, do it the other way around, create secrets and add namespaces to them.
values.yaml
templates/namespaces.yaml
templates/secrets.yaml
Result:
More informations about Flow Control(if,else if,range) can be found here.