How to parse String to Boolen value in Jsonnet

1.9k views Asked by At

I have a jsonnet function that accepts boolean values as parameters. Suppose I have a jsonnet file called deploy.jsonnet:

function (image='', isReady) {
local config = self,
deploy: if isReady then [ do deployment ]
else [don't do deployment]

I pass values to this function like:

jsonnet -A name=new-deployment -A isReady=true deploy.jsonnet

but the problem is that -A always provides values as String so the conditional check will fail with the message:

RUNTIME ERROR: Condition must be boolean, got string.
    ./deploy.jsonnet:(133:45)-(148:15)  object <anonymous>
    During manifestation

Also I didn't see an option to parse a string to boolean value.

Question is - is there any way to pass boolean value to a function in jsonnet or can we parse a string to boolean?

2

There are 2 answers

1
sbarzowski On BEST ANSWER

Yes, it is possible, through --tla-code (instead of -A), e.g.:

jsonnet -A name=new-deployment --tla-code isReady=true deploy.jsonnet

The difference is that instead of treating the value as a string, it treats it as jsonnet code. So it's also possible to pass objects, arrays and even functions this way.

Regarding converting string to boolean. While I think there is no builtin way to do that, it's quite easy to roll your own function:

local stringToBool(s) =
  if s == "true" then true
  else if s == "false" then false
  else error "invalid boolean: " + std.manifestJson(s);
0
Anoop Philip On

jsonnet doesn't support to provide a value as boolean and also it doesn't support parsing a string to boolean value so I've changed parameter type to String and does a String comparison to solve the above issue with boolean parsing

function (image='', isReady='') {
local config = self,
deploy: if (isReady == 'true') then [ do deployment ]
else [don't do deployment]