Home > Enterprise >  Remove new line at the beginning of the file - Go template
Remove new line at the beginning of the file - Go template

Time:09-05

I'm using fallowing loop to generate credentials file in Hashicorp Vault. All works well but I'm getting one new line at the beginning of the file. How can I remove it?

vault.hashicorp.com/agent-inject-template-credentials.txt: |
  {{- with secret (print "secret/data/test/config") }}{{- range $k, $v := .Data.data }}
  {{ $k }}: {{ $v }}
  {{- end }}{{- end }}

Input: map[test1:test1 test2:test2 test3:test3]

Current output:

// one empty line at the beginning
test1: test1
test2: test2
test3: test3

CodePudding user response:

Your template contains a newline before rendering the elements, use the - sign to get rid of that:

{{- with secret (print "secret/data/test/config") }}{{- range $k, $v := .Data.data -}}
{{ $k }}: {{ $v }}
{{- end }}{{- end }}

Note the added - sign at the end of the first line.

This of course will render each pair on the same line. Leave the newline at the end of rendering the elements by removing the - sign from the beginning of the last line:

{{- with secret (print "secret/data/test/config") }}{{- range $k, $v := .Data.data -}}
{{ $k }}: {{ $v }}
{{ end }}{{- end }}

Alternatively you can move the first added - sign to the beginning of the second line:

{{- with secret (print "secret/data/test/config") }}{{- range $k, $v := .Data.data }}
{{- $k }}: {{ $v }}
{{ end }}{{- end }}

These templates will output (no first empty line):

test1: test1
test2: test2
test3: test3

Try it on the Go Playground.

  • Related