1

I am attempting to create a kubernetes ConfigMap with helm, which simply consists of the first line within a config file. I put my file in helm/config/file.txt, which has several lines of content, but I only want to extract the first. My first attempt at this was to loop over the lines of the file (naturally), but quit out after the first loop:

apiVersion: v1
kind: ConfigMap
metadata:
  name: one-line-cm
data:
  first-line:
    {{- range .Files.Lines "config/file.txt" }}
    {{ . }}
    {{ break }} # not a real thing
    {{- end }}

Unfortunately, break doesn't seem to be a concept/function in helm, even though it is within golang. I discovered this the hard way, as well as reading about a similar question in this other post: Helm: break loop (range) in template

I'm not stuck on using a loop, I'm just wondering if there's another solution to perform the simple task of extracting the first line from a file with helm syntax.

tubensandwich
  • 128
  • 1
  • 1
  • 7

1 Answers1

2

EDIT:
I've determined the following is the cleanest solution:

.Files.Lines "config/file.txt" | first

(As a side note, I had to pipe to squote in my acutal solution due to my file contents containing special characters)


After poking around in the helm docs for alternative functions, I came up with a solution that works, it's just not that pretty:

apiVersion: v1
kind: ConfigMap
metadata:
  name: one-line-cm
data:
  first-line: |
    {{ index (regexSplit "\\n" (.Files.Get "config/file.txt") -1) 0 }}

This is what's happening above (working inside outward):

  1. .Files.Get "config/file.txt" is returning a string representation of the file contents.
  2. regexSplit "\\n" <step-1> -1 is splitting the file contents from step-1 by newline (-1 means return the max number of substring matches possible)
  3. index <step-2> 0 is grabbing the first item (index 0) from the list returned by step-2.

Hope this is able to help others in similar situations, and I am still open to alternative solution suggestions.

tubensandwich
  • 128
  • 1
  • 1
  • 7
  • 1
    Using a couple of the [Sprig](http://masterminds.github.io/sprig/) functions, does `.Files.Get "config/file.txt" | splitList "\n" | first` work? `regexFind "[^\n]*"` might also work (find the first block of characters that doesn't contain a newline). – David Maze May 12 '22 at 10:22
  • @DavidMaze, yes, actually, both of those also work, and are a bit cleaner, thanks! For completeness, this is the entire latter solution you suggested: `regexFind "[^\n]*" (.Files.Get "config/file.txt")` . You mentioning `first` actually made me think of this solution (which I think I will mark as the "answer"): `.Files.Lines "config/file.txt" | first`. It's so obvious now, but took a lot of brainstorming. Thanks for the help :) – tubensandwich May 12 '22 at 16:14