简体   繁体   中英

kubernetes YML, use for loop

Is there a mechanism in a template (yml) file in k8s for generating multiple items? Like a for loop.

For example , I have a template used my multiple projects. But some need 1 database others maybe 2, 3 or more. I don't want to define all variables by hands, and edit my file if a new projects comes in and needs a new variable.

Example of what I do today:

  template:
      (...)
      containers:
        (...)
        env:
        - name: DATABASE_NAME
          value: "{{prj.database.name}}"
        - name: DATABASE_NAME_2
          value: "{{prj.database.name.second}}"
        - name: DATABASE_USER
          valueFrom:
            secretKeyRef:
              name: "{{ k8s.deploy.app.secret.name }}"
              key: database_user
        - name: DATABASE_USER_2
          valueFrom:
            secretKeyRef:
              name: "{{ k8s.deploy.app.secret.name }}"
              key: database_user_2

As you can see I have to copy paste code for each user + password + database name. In this file and also in secrets. I use XLDeploy to insert data in my YML files.

What i'm looking for:

  template:
      (...)
      containers:
        (...)
        env:
        ---- for i in {{prj.database.number}} ----
        - name: DATABASE_NAME_{i}
          value: "{{prj.database.name.{i]}}"
        - name: DATABASE_USER_{i}
          valueFrom:
            secretKeyRef:
              name: "{{ k8s.deploy.app.secret.name }}"
              key: database_user_{i}
        ---- end for loop ----

So I could insert in XLDeploy my number of databases to use for each projects. And fill the values with XLD too.

Is that possible, or I need to use a script langague to generate a YML file from a "YML template" ?

You could use helm for this if you have other yamls related to this file. Helm allows for syntax like this:

{{- range .Values.testvalues }}
---
apiVersion: v1
kind: Service
metadata:
  annotations: {}
  labels: {}
  name: {{ . }}
spec:
  ports:
  - name: tcp-80-8080
    port: 80
    protocol: TCP
    targetPort: 8080
  selector: 
    app: rss-{{ . }}
  type: ClusterIP
{{- end }}

So with a list for testvalues in the values.yaml like this:

testvalues:
- a
- b
- c
- d

Helm would generate four service declarations -- one for each item. The first looking like this:

---
apiVersion: v1
kind: Service
metadata:
  annotations: {}
  labels: {}
  name: a
spec:
  ports:
  - name: tcp-80-8080
    port: 80
    protocol: TCP
    targetPort: 8080
  selector: 
    app: rss-a
  type: ClusterIP

The other option if it's just a single file, is to use Jinja and something like Python to build the file using the jinja2 module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM