Introduction
Problem
When configuring the Vault agent, if the secret being read is a KV secret that uses a dash character ("-") in the key name for the secret, the Vault Agent will throw an error when attempting to render the template to a file.
As an example, we have here a KV secret that uses a dash in its key value:
vault kv put kv/password pass-word=1234
We then have a Vault Agent configured to read the secret using the following template:
{{ with secret "kv/data/password" }}
{{ .Data.data.pass-word }}
{{ end }}
When the Vault agent starts, it will throw an error similar to the following
[ERROR] template.server: template server error: error="/vault/agent/template.ctmpl: parse: template: :2: bad character U+002D '-'"
Prerequisites
- Vault Agent (any version)
- A KV secret that uses a dash character in the key value e.g. vault kv put kv/password pass-word=1234
Cause
-
Vault agent templates relies on Consul templating markup. Consul templating markup in turn relies on the Go template package and format. In the Go template package, the inability to directly use a dash ("-") in key values is a known feature gap that has been acknowledged by the maintainers of the package. Further discussion can be found here.
Overview of possible solutions (if applicable)
- The consensus recommendation for working around this issue is to instead use the index function which is a built-in feature of the go template package. So, for the example above that was previously throwing the template server error
{{ with secret "kv/data/password" }}
{{ .Data.data.pass-word }}
{{ end }}
We can instead use the following syntax to grab the value
{{ with secret "kv/data/password" }}
{{ index .Data.data "pass-word"}}
{{ end }}
Outcome
Secret is successfully rendered via the Vault agent.