我无法理解如何最好地参数化Jsonnet文件,以便我可以从bash和另一个Jsonnet文件调用相同的文件.
假设我有一个名为template.jsonnet的简单模板:
{
// Required arguments
name:: error "'name' must be specified",
port:: error "'port' must be specified",
...,
}
Run Code Online (Sandbox Code Playgroud)
我可以很容易地将它合并到另一个Jsonnet文件中,并提供其所需的参数值:
{
local template = = import "./template.jsonnet";
template + {
name:: "service",
port:: 8080,
}
Run Code Online (Sandbox Code Playgroud)
我正在努力确定我可以template.jsonnet从bash 调用以获得相同结果的预期方式.
我可以使用,--ext-str但似乎需要std.extVar(x)
GitHub 问题表明它--tla-code可能是std.extVar()的替代品,但我不明白如何根据我的需要使用它.
后续问题是:如何对参数这是一个数组:
{
local template = = import "./template.jsonnet";
template + {
name:: "service",
port:: [8080,8081,8082],
}
Run Code Online (Sandbox Code Playgroud)
最直接的方法是使用一些内联jsonnet:
jsonnet -e '(import "template.jsonnet") + { name: "service", port: 8080 }'
Run Code Online (Sandbox Code Playgroud)
为了便于参数化,您可以使用extVars或顶级参数(TLA).
jsonnet -e 'function(name, port) (import "template.jsonnet") + { name: name, port: port }' --tla-str name="blah" --tla-code port='[8080, 8081]'
Run Code Online (Sandbox Code Playgroud)
要么
jsonnet -e '(import "template.jsonnet") + { name: std.extVar("name"), port: std.extVar("port") }' --ext-str name="blah" --ext-code port='[8080, 8081]'
Run Code Online (Sandbox Code Playgroud)
更好的方法是使template.jsonnet成为一个函数并使用--tla-code/ --tla-str:
function(name, port) {
name:: name,
port:: port
// Sidenote: the fields are hidden here, because they use ::,
// use : to make them appear when the object is manifested.
// Sidenote 2: You can provide default argument values.
// For example function(name, port=8080) makes port optional.
}
Run Code Online (Sandbox Code Playgroud)
然后在另一个jsonnet文件中,您可以按如下方式使用它:
local template = import "./template.jsonnet";
{
filled_template: template(
name="service",
port=8080 // or port=[8080,8081,8082]
)
}
Run Code Online (Sandbox Code Playgroud)
您可以使用shell中的模板,如下所示:
jsonnet --tla-code name='"some name"' --tla-code port=8080 template.jsonnet
Run Code Online (Sandbox Code Playgroud)
请注意名称是如何引用标记的(没有外部'它们将被shell解释).那是因为你可以传递任何评估为任何类型的jsonnet代码tla-code.
如果你想逐字传递一个字符串,你可以使用--tla-str:
jsonnet --tla-str name="some name" --tla-code port=8080 template.jsonnet
Run Code Online (Sandbox Code Playgroud)
另一方面,您可以将数组(或对象或任何jsonnet代码)传递给--tla-code:
jsonnet --tla-code name='"some name"' --tla-code port='[8080, 8081, 8082]' template.jsonnet
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想更改自己template.jsonnet,可以使用包装器文件来提供我所描述的界面:
template_func.jsonnet:
local template = import "./template.jsonnet";
function(name, port) template + {
name: name,
port: port
}
Run Code Online (Sandbox Code Playgroud)