jsonnet

How to use local variables in object comprehension


I'm trying to do the following:

main.jsonnet

local data = import 'data.libsonnet';
{
    ["build:"+client]: {
        variables: data.getVariables(client, "build")
    }
    for client in data.clients
}

data.libsonnet

getVariables(client, stage) ::
{
    local neededVars =  
        if stage == "build" then ["var1", "var2"]
        else if stage == "test" then ["var2"]
        else []
    [varName]: $.dict[client][varName]
    for varName in neededVars

}
dict:: {
    "customer1": { "var1: "value", "var2": "value2" }
} 

But the problem is that whatever I try to code the reference to neededVars (also tried using self.), I get Error: Unknown Variable. If I return an object instead of just an array, eg. with

getVariables(client, stage) ::
{
    local neededVars =  
        if stage == "build" then ["var1", "var2"]
        else if stage == "test" then ["var2"]
        else []

    variables: {
        [varName]: $.dict[client][varName]
        for varName in neededVars
    }
}

then the local variable is accessible. But then, of course, the output is not the desired one.

Can you tell me, why the variable is not accessible if I just want to return an Array and how is the syntax to access it?

Thx very much!


Solution

  • You can define a local pretty much anywhere, but it’s not accessible in the context of a comprehension. I can’t explain why, but my assumption is that the definition of the outer scope is not yet complete, so the local is not visible to the comprehension.

    What happens if you try moving it outside the object but still within the function?

    getVariables(client, stage) ::
        local neededVars =  
            if stage == "build" then ["var1", "var2"]
            else if stage == "test" then ["var2"]
            else [];
        {
            variables: {
                [varName]: $.dict[client][varName]
                for varName in neededVars
            }
        }
    

    That way the local is outside the scope of the object definition, but still in the function scope and the passed parameters are accessible.