给定以下数组:
// use strings only in the form <protocol>-<port>
ports: [
'tcp-1514',
'tcp-8080',
'tcp-8443',
],
我正在尝试编写 jsonnet 来拆分数组的每个元素以生成此对象(在 yaml 中表示):
ports:
- name: "tcp-1514"
containerPort: 1514
protocol: "tcp"
- name: "tcp-8080"
containerPort: 8080
protocol: "tcp"
- name: "tcp-8443"
containerPort: 8443
protocol: "tcp"
我已经尝试了几次数组理解的迭代来做到这一点,请注意我是 jsonnet 的新手。最新的迭代是这样的:
ports: [
{
local proto, port ::= std.split(port_obj, '-');
name: port_obj,
containerPort: port,
protocol: proto,
} for port_obj in $.sharedConfig.ports,
]
$.sharedConfig.ports
端口分配在哪里。问题是local proto, port ::= std.split(port_obj, '-');
。我不确定这是有效的代码。解释器正在大便它,我找不到任何示例或文档表明这是有效的。
最终,如果它无效,那么我将不得不 split() 两次,但这将是不幸的。例如,这有效:
{
local ports = ['tcp-1514', 'tcp-8080', 'tcp-8443',],
ports: [
local port = std.split(name,'-')[1];
local proto = std.split(name,'-')[0];
{
name: name,
protocol: proto,
containerPort: port,
}
for name in ports],
}
产生:
{
"ports": [
{
"containerPort": "1514",
"name": "tcp-1514",
"protocol": "tcp"
},
{
"containerPort": "8080",
"name": "tcp-8080",
"protocol": "tcp"
},
{
"containerPort": "8443",
"name": "tcp-8443",
"protocol": "tcp"
}
]
}
和 YAML:
---
ports:
- containerPort: '1514'
name: tcp-1514
protocol: tcp
- containerPort: '8080'
name: tcp-8080
protocol: tcp
- containerPort: '8443'
name: tcp-8443
protocol: tcp
...但我真的不喜欢两行变量赋值。我对此进行的测试越多,我就越相信我确定单行分配不可行是正确的。
谁能告诉我我错了,我真的很感激。