0

In consul-template I want to pass a ENV var with with new lines that will be expanded so "hello\nworld" is shown as:

hello
world

command: VARIABLE="hell\nworld" consul-template -template "in.tpl:out.txt" -once && cat out.txt

template file: {{ env "VARIABLE" }}

however I am getting

hello\nworld

If I debug the template I am showed the \n has been escaped to \\n:

{{ env "VARIABLE" | spew_dump }}

"hello\\nworld"
henry.oswald
  • 5,304
  • 13
  • 51
  • 73

1 Answers1

1

In consul-template

{{ env "VARIABLE" | replaceAll "\\n" "\n" }}

Given the new-line is as a C-Escape \n in a golang double quoted string literal, there is the replaceAll consul template function1 readily available (similar to env) to replace \n with U+000A New Line (Nl) line feed (lf) , end of line (eol) , LF.

This is the format as shown by the spew_dump in question.

Note that this replaces \n only, not \r nor the other escape sequences.


In Shell (earlier)

There is no \n C-Escape in double-quoted strings like "hello\nworld" , but printf(1) has it - or - if your shell supports them, $'' strings (bash, zsh/z-shell).

Compare with How can I have a newline in a string in sh?.

Examples:

Example #1: $'' quoted string

VARIABLE=$'hello\nworld' consul-template -template "in.tpl:out.txt" -once && cat out.txt

Example #2: printf(1)

VARIABLE="$(printf "hello\nworld")" consul-template -template "in.tpl:out.txt" -once && cat out.txt

Mind that command substitution ($(...)) may remove a trailing newline.


  1. https://github.com/hashicorp/consul-template/blob/378ee4bf907cae0d41eebf6a854f5539a7de1987/template/funcs.go#L1173-L1177
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Thanks, I am trying to get the newline inside th of the in.tml file rather than modify it in the variable def. These values could come from env vars or different data sources. – henry.oswald Dec 18 '22 at 21:48
  • @henry.oswald: Ah, if you don't want to change early in the environment variables, you can replace within the template. I'd suggest `replaceAll` in my edit. The first double-slash is by intention as necessary, comare with the spew output. – hakre Dec 19 '22 at 11:53
  • thanks, ideally i wouldn't have todo find replaces to insert this string. Is it possible to these variables without backslash being escaped? – henry.oswald Dec 19 '22 at 12:20
  • Sure, that is the "In Shell (earlier)" section, earlier not only in time of the answer but also _before_ passing it into the template ;). What are the different data-sources? Already in the environment or probably env files? Please give a bit more context. – hakre Dec 19 '22 at 13:36