Better loop variable state handling

* Loops caused local scripts variables to be backed up then restored,
    which would have caused a set_var in a loop to have no effect.
  * Instead, we back up the state of the variable (existing or not,
    value) and either restore the original value or delete the variable
    if it didn't exist.
This commit is contained in:
Emmanuel BENOîT 2022-09-04 22:54:03 +02:00
parent 1b1c1281a2
commit a5b1ac5c4c

View file

@ -220,9 +220,13 @@ class RcInstruction(abc.ABC):
if self._loop is None:
self._display.vvvv("%s : running action %s" % (host_name, self._action))
return self.run_once(host_name, merged_vars, host_vars, script_vars)
loop_values = self.evaluate_loop(host_name, merged_vars)
script_vars = script_vars.copy()
for value in loop_values:
# Save previous loop variable state
had_loop_var = self._loop_var in script_vars
if had_loop_var:
old_loop_var = script_vars[self._loop_var]
try:
# Loop over all values
for value in self.evaluate_loop(host_name, merged_vars):
self._display.vvvv(
"%s : running action %s for item %s"
% (host_name, self._action, repr(value))
@ -232,6 +236,12 @@ class RcInstruction(abc.ABC):
if not self.run_once(host_name, merged_vars, host_vars, script_vars):
return False
return True
finally:
# Restore loop variable state
if had_loop_var:
script_vars[self._loop_var] = old_loop_var
else:
del script_vars[self._loop_var]
def run_once(self, host_name, merged_vars, host_vars, script_vars):
if self.evaluate_condition(host_name, merged_vars):