最直接的方法是使用一些内联的jsonnet:
jsonnet -e '(import "template.jsonnet") + { name: "service", port: 8080 }'
为了更轻松地进行参数化,您可以使用 extVars 或顶级参数 (TLA)。
jsonnet -e 'function(name, port) (import "template.jsonnet") + { name: name, port: port }' --tla-str name="blah" --tla-code port='[8080, 8081]'
或
jsonnet -e '(import "template.jsonnet") + { name: std.extVar("name"), port: std.extVar("port") }' --ext-str name="blah" --ext-code port='[8080, 8081]'
更好的办法是把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.
}
然后在另一个jsonnet文件中可以这样使用:
local template = import "./template.jsonnet";
{
filled_template: template(
name="service",
port=8080 // or port=[8080,8081,8082]
)
}
您可以使用 shell 中的模板,如下所示:
jsonnet --tla-code name='"some name"' --tla-code port=8080 template.jsonnet
注意名称如何需要引号(如果没有外部',它们将由shell 解释)。那是因为您可以将任何 jsonnet 代码传递给 tla-code 中的任何类型。
如果你想逐字传递一个字符串,你可以使用--tla-str:
jsonnet --tla-str name="some name" --tla-code port=8080 template.jsonnet
另一方面,您可以将数组(或对象,或任何 jsonnet 代码)传递给--tla-code:
jsonnet --tla-code name='"some name"' --tla-code port='[8080, 8081, 8082]' template.jsonnet
或者,如果您不想更改您的template.jsonnet,您可以使用包装文件来提供我描述的接口:
template_func.jsonnet:
local template = import "./template.jsonnet";
function(name, port) template + {
name: name,
port: port
}