consul-template expand new lines from env var

783 views Asked by At

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"
1

There are 1 answers

4
hakre On

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