Overview
When using Nomad Variables and nomad-pack template blocks to inject environment variables into a container, users may notice that double quotes (") inside the variable value are lost at runtime. This article explains how to preserve double quotes in the final environment variable.
Use Case
You want to store a JSON-formatted string as an environment variable (e.g., for logging configuration) in a Nomad Variable and inject it into a container at runtime using a Nomad Pack template.
Template Configuration
In your Nomad Pack, you use a template block to pull environment variables from the Nomad Variable store and inject them into the task:
template {
data = <<EOH
{{ if nomadVarExists "nomad/jobs/[[ .service.name ]]@[[ .service.namespace ]]" }}
{{ with nomadVar "nomad/jobs/[[ .service.name ]]@[[ .service.namespace ]]" -}}
{{ range .Tuples -}}
{{ .K }}={{ .V }}
{{ end }}
{{- end }}
{{ end }}
EOH
destination = "${NOMAD_SECRETS_DIR}/env"
env = true
change_mode = "noop"
}nomadVarExists and nomadVar check and retrieve the variable.
.Tuples iterates over key-value pairs.
env = true ensures the rendered file is injected as environment variables.
The Problem
When storing a JSON string in a Nomad Variable like this:
{
"APP_LOG_FORMAT": "\"log_json '{\"timestamp\": \"$time\", \"level\": \"$level\", \"message\": \"$msg\"}'\""
}You may find that the resulting environment variable inside the container appears as:
APP_LOG_FORMAT=log_json {timestamp: $time, level: $level, message: $msg}This happens because Nomad template rendering unescapes quotes, leading to malformed JSON.
However, the requirement is of below expected format:-
APP_LOG_FORMAT=log_json '{"timestamp": "$time", "level": "$level", "message": "$msg"}'The Solution: Double-Escape Quotes
To preserve double quotes in the final environment variable, you must double-escape them in the Nomad Variable:
{
"APP_LOG_FORMAT": "\"log_json '{\\\"timestamp\\\": \\\"$time\\\", \\\"level\\\": \\\"$level\\\", \\\"message\\\": \\\"$msg\\\"}'\""
}This ensures that when the template renders and the shell interprets the variable, the correct format is preserved:
APP_LOG_FORMAT=log_json '{"timestamp": "$time", "level": "$level", "message": "$msg"}'
References
https://developer.hashicorp.com/nomad/docs/concepts/variables
https://developer.hashicorp.com/nomad/docs/reference/runtime-environment-settings
https://developer.hashicorp.com/nomad/tools/nomad-pack