loop thru lines of plain text file passed by --set-file helm option then parse each line by column

4/10/2020

I have a cron file and i am trying to pass it thru --set-file option. I want to loop thru the cron file lines and create for each line new Kubernetes Object of kind CronJob.

I used it like this helm instal ... --set-file crons.file=mycron

where mycron file looks like a typical cron file:

0,10,20,30,40,50 * * * * /usr/bin/cmd1 opta optb
35 2-23/3 * * * /usr/bin/cmd2

i am not able to iterate thru lines of this simple plain text :

{{- range $indx, $line := .Values.crons.file }}
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: {{ regexFind "[^/]+
quot;
"$line"}} jobTemplate: spec: template: spec: containers: - name: cron-{{ $indx }} image: busybox args: - /bin/sh - -c - {{ regexFind "[^/]+
quot;
"$line"}} restartPolicy: OnFailure {{- end }}

Is there a function like fromYaml which makes a plain text file iterable by range function ?

-- Abdennour TOUMI
kubernetes
kubernetes-helm
sprig-template-functions

1 Answer

4/11/2020

The Sprig support library includes functions for splitting and joining strings into lists, and for manipulating lists in general. If splitList the file on newlines, you'll get a list of lines. You can again splitList each line on spaces to get the separate time and command parts out of the individual cron lines.

{{/* Iterate over individual lines in the string */}}
{{- range $line := splitList "\n" .Values.crons.file -}}

{{/* Break the line into words */}}
{{- $words := splitList " " $line -}}

{{/* Reconstitute the schedule and command parts from the words */}}
{{- $time := slice $words 0 5 | join " " -}}
{{- $command := slice $words 5 -}}

---
schedule: {{ $time }}
command: {{- $command | toYaml | nindent 2}}
{{ end -}}
-- David Maze
Source: StackOverflow