Gomplate : bad character U+0022 '-'

Viewed 5306

I was trying out gomplate and encountered an error.

For context I've defined a template file, test.tmplt, and a datasource file, dev.yaml.
test.tmplt has the following content :

localAPIEndpoint:
    advertiseAddress: {{ (datasource "k8s").api-advertise-ip }}

while dev.yaml contains the following :

api-advertise-ip: 192.168.0.1

If I try to fill in the content of test.tmplt using gomplate like so :

gomplate -d k8s=./dev.yaml -f ./test.tmplt -o test.conf

I get the following error :

09:42:44 FTL  error="template: ./test.tmplt:2: bad character U+002D '-'"

Seems to me that it does not like the '-' symbol in the template file. Any workaround?Is it the intended behaviour?

Edit 1: Thanks @icza for the answer which works correctly for the example above. Yet if I modify the yaml file to have nested fields it seems to break down.
For example

dev.yaml :

kubernetes:
    api-advertise-ip: 192.168.0.0

test.tmplt :

localAPIEndpoint:
    advertiseAddress: {{ index (datasource "k8s") "kubernetes.api-advertise-ip" }}

In this case the output of :

gomplate -d k8s=./dev.yaml -f ./test.tmplt -o test.conf

is :

localAPIEndpoint:
    advertiseAddress: <no value>
2 Answers

Your "k8s" data source is a YAML config, and you want to access the api-advertise-ip property of it.

Since api-advertise-ip contains dashes, you can't use the name as-is in the template, because that's a syntax error: the template engine tries to use api as the property name, and the dash after that is a syntax error.

You have to put the property name in quotes that contains dashes: "api-advertise-ip", but this using the . selector is also invalid syntax.

Use the builtin index function to index the YAML datasource with this key:

localAPIEndpoint:
    advertiseAddress: {{ index (datasource "k8s") "api-advertise-ip" }}

gomplate uses text/template under the hood, see a working example on the Go Playground.

When using index and you have multiple nested levels, provide each key as an additional parameter to index.

For example:

localAPIEndpoint:
    advertiseAddress: {{ index (datasource "k8s") "kubernetes" "api-advertise-ip" }}

Try this one on the Go Playground.

For those landing here for accessing values from Kubernetes secret (with kubectl) whose keys have hyphen - in them, the solution as suggested by @icza is:

kubectl -n <namespace> \
        get secret <secret-name>  \
        -ogo-template='{{ index .data "key-with-hyphens" | base64decode }}'
Related