Is there a simple way to grab the first line from a file with helm?

Issue

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.

Solution

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.

Answered By – tubensandwich

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.