Skip to content

Commit 9d8235b

Browse files
Add ability to do implicit nested loops on a "getValue"
The implicit nested loops are defined using a "*". For example, we can now iterate over all the container names by doing ".spec.containers.*.name"
1 parent bee57f0 commit 9d8235b

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

generic_k8s_webhook/operators.py

+15
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,9 @@ def _get_value_from_json(self, data: Union[list, dict], path: list):
319319
if len(path) == 0 or path[0] == "":
320320
return data
321321

322+
if path[0] == "*":
323+
return self._evaluate_wildcard(data, path)
324+
322325
if isinstance(data, dict):
323326
key = path[0]
324327
if key in data:
@@ -332,6 +335,18 @@ def _get_value_from_json(self, data: Union[list, dict], path: list):
332335

333336
return None
334337

338+
def _evaluate_wildcard(self, data: Union[list, dict], path: list):
339+
if not isinstance(data, list):
340+
raise RuntimeError(f"Expected list when evaluating '*', but got {data}")
341+
l = []
342+
for elem in data:
343+
sublist = self._get_value_from_json(elem, path[1:])
344+
if isinstance(sublist, list):
345+
l.extend(sublist)
346+
else:
347+
l.append(sublist)
348+
return l
349+
335350
def input_type(self) -> type | None:
336351
return None
337352

tests/conditions_test.yaml

+30
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,36 @@ test_suites:
138138
spec: {}
139139
- name: bar
140140
expected_result: foo
141+
# Evaluate a wildcard (1)
142+
- condition:
143+
getValue: .nodeAffinity.preferredDuringSchedulingIgnoredDuringExecution.*.preference.matchExpressions
144+
context:
145+
- nodeAffinity:
146+
preferredDuringSchedulingIgnoredDuringExecution:
147+
- preference:
148+
matchExpressions:
149+
- key: key1
150+
- preference:
151+
matchExpressions:
152+
- key: key2
153+
expected_result:
154+
- key: key1
155+
- key: key2
156+
# Evaluate a wildcard (2)
157+
- condition:
158+
getValue: .nodeAffinity.preferredDuringSchedulingIgnoredDuringExecution.*.preference.matchExpressions.*.key
159+
context:
160+
- nodeAffinity:
161+
preferredDuringSchedulingIgnoredDuringExecution:
162+
- preference:
163+
matchExpressions:
164+
- key: key1
165+
- preference:
166+
matchExpressions:
167+
- key: key2
168+
expected_result:
169+
- key1
170+
- key2
141171
- name: FOR_EACH
142172
tests:
143173
- schemas: [v1alpha1]

0 commit comments

Comments
 (0)