Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

arithmetic functions unable to handle implicit / dynamic type conversion #611

Open
JPvRiel opened this issue Oct 5, 2017 · 3 comments
Open
Labels

Comments

@JPvRiel
Copy link

JPvRiel commented Oct 5, 2017

It's great to see #576 was resolved.

A next stumbling block for this feature is wrong type for value; expected type errors. For example, it seems getenv will always return a string, even if the content in the env var is indeed a valid number.

Set this env:

export s1=10
export s2=2

And given this template:

{{ $s1 := getenv "s1" -}}
{{ $s2 := getenv "s2" -}}
Inline division is {{ $s1 }} \ {{ $s2 }} = {{ div $s1 $s2 }}.

The error is wrong type for value; expected int; got string results.

Looking at https://github.com/hashicorp/consul-template/blob/master/template/funcs.go, one can see they worked past type issues by 'heavier' arithmentic functions using https://golang.org/pkg/reflect/ to do dynamic type conversion.

Unfortunately, template writers for confd are not always in control how how the type in the datastore is set, so whether json or environment vars, getting integers, floats, etc stored as strings is probably common.

@okushchenko okushchenko added the bug label Oct 5, 2017
@okushchenko
Copy link
Collaborator

Thanks for reporting it. I'll review the functions in consul-template and consider either importing them or changing some functions in confd.

@disaster37
Copy link

Hi,

we have the same need as describe by @JPvRiel.
have you any trick to convert string to int with confd 0.14.0 (to stay the enhance) ?

@JPvRiel
Copy link
Author

JPvRiel commented Oct 21, 2017

have you any trick to convert string to int with confd 0.14.0

Not me. For docker use cases, the only way I can think to work around it is with an entrypoint script that uses bash, bc, and printf to do the math and set an env var. It's messy because bc has fixed scale format, so printf is needed to reformat the scale (e.g. bc -l has scale of 20, but I don't want bc output with trailing zeros like .500000.... To get 1 / 2 = 0.5:

a=1; b=2; x=$(printf "%.20g" $(echo "$a / $b" | bc -l))

Then you can use getenv in confd...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants