Skip to content

Commit 547abc0

Browse files
committed
using regex for path split
1 parent 540e0d8 commit 547abc0

File tree

3 files changed

+32
-28
lines changed

3 files changed

+32
-28
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
---
2+
bugfixes:
3+
- Fix update_fact to update a fact where a key in the referenced path contains a bracket.

plugins/action/update_fact.py

Lines changed: 16 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -70,39 +70,27 @@ def _field_split(path):
7070
:return: the individual parts of the path
7171
:rtype: list
7272
"""
73-
que = list(path)
74-
val = que.pop(0)
73+
que = path
7574
fields = []
76-
try:
77-
while True:
78-
field = ""
79-
# found a '.', move to the next character
80-
if val == ".":
81-
val = que.pop(0)
82-
# found a '[', pop until ']' and then get the next
83-
if val == "[":
84-
val = que.pop(0)
85-
while val != "]":
86-
field += val
87-
val = que.pop(0)
88-
val = que.pop(0)
89-
else:
90-
while val not in [".", "["]:
91-
field += val
92-
val = que.pop(0)
93-
try:
94-
# make numbers numbers
95-
fields.append(ast.literal_eval(field))
96-
except Exception:
97-
# or strip the quotes
98-
fields.append(re.sub("['\"]", "", field))
99-
except IndexError:
100-
# pop'ed past the end of the que
101-
# so add the final field
75+
# regex match dotted values and square brackets
76+
regex = re.compile(r'^[^\[\].]+|^\[[\'\"].+?[\'\"]\]|^\[.+?\]')
77+
while (regex.match(que)):
78+
m = regex.match(que)
79+
# remove outer square brackets
80+
field = re.sub(r'(^\[)|(\]$)', "", que[m.start():m.end()])
10281
try:
82+
# make numbers numbers
10383
fields.append(ast.literal_eval(field))
10484
except Exception:
85+
# or strip the quotes
10586
fields.append(re.sub("['\"]", "", field))
87+
try:
88+
if que[m.end()] == '.':
89+
que = que[m.end() + 1:]
90+
else:
91+
que = que[m.end():]
92+
except IndexError:
93+
que = ''
10694
return fields
10795

10896
def set_value(self, obj, path, val):

tests/integration/targets/utils_update_fact/tasks/main.yaml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
c:
77
- 1
88
- 2
9+
d:
10+
"[bracket_key]": bracket_value
11+
key: value
912

1013
- name: Update the fact
1114
ansible.utils.update_fact:
@@ -14,6 +17,10 @@
1417
value: 10
1518
- path: "a['b']['c'][1]"
1619
value: 20
20+
- path: "a['b'][d]['[bracket_key]']"
21+
value: new_bracket_value
22+
- path: "a['b'][d]['key']"
23+
value: new_value
1724
register: updated
1825

1926
- name: Assert
@@ -26,6 +33,9 @@
2633
c:
2734
- 10
2835
- 20
36+
d:
37+
"[bracket_key]": new_bracket_value
38+
key: new_value
2939

3040
- name: Update the fact
3141
ansible.utils.update_fact:
@@ -70,3 +80,6 @@
7080
c:
7181
- 1
7282
- 20
83+
d:
84+
"[bracket_key]": bracket_value
85+
key: value

0 commit comments

Comments
 (0)