Skip to content

Commit

Permalink
Add ability to do implicit nested loops on a "getValue"
Browse files Browse the repository at this point in the history
The implicit nested loops are defined using a "*". For example, we can
now iterate over all the container names by doing
".spec.containers.*.name"
  • Loading branch information
jordipiqueselles committed Apr 22, 2024
1 parent bee57f0 commit 24ea679
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
15 changes: 15 additions & 0 deletions generic_k8s_webhook/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,9 @@ def _get_value_from_json(self, data: Union[list, dict], path: list):
if len(path) == 0 or path[0] == "":
return data

if path[0] == "*":
return self._evaluate_wildcard(data, path)

if isinstance(data, dict):
key = path[0]
if key in data:
Expand All @@ -332,6 +335,18 @@ def _get_value_from_json(self, data: Union[list, dict], path: list):

return None

def _evaluate_wildcard(self, data: Union[list, dict], path: list):
if not isinstance(data, list):
raise RuntimeError(f"Expected list when evaluating '*', but got {data}")
l = []
for elem in data:
sublist = self._get_value_from_json(elem, path[1:])
if isinstance(sublist, list):
l.extend(sublist)
else:
l.append(sublist)
return l

def input_type(self) -> type | None:
return None

Expand Down
30 changes: 30 additions & 0 deletions tests/conditions_test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,36 @@ test_suites:
spec: {}
- name: bar
expected_result: foo
# Evaluate a wildcard (1)
- condition:
getValue: .nodeAffinity.preferredDuringSchedulingIgnoredDuringExecution.*.preference.matchExpressions
context:
- nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference:
matchExpressions:
- key: key1
- preference:
matchExpressions:
- key: key2
expected_result:
- key: key1
- key: key2
# Evaluate a wildcard (2)
- condition:
getValue: .nodeAffinity.preferredDuringSchedulingIgnoredDuringExecution.*.preference.matchExpressions.*.key
context:
- nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference:
matchExpressions:
- key: key1
- preference:
matchExpressions:
- key: key2
expected_result:
- key1
- key2
- name: FOR_EACH
tests:
- schemas: [v1alpha1]
Expand Down

0 comments on commit 24ea679

Please sign in to comment.