ansible: split environment editing into a separate class.

This commit is contained in:
David Wilson 2018-03-27 15:02:32 +05:45
parent fccca54068
commit cd1683b924
1 changed files with 25 additions and 18 deletions

View File

@ -112,6 +112,17 @@ def module_fixups(mod):
mod.YumRepo.repofile = mod.configparser.RawConfigParser() mod.YumRepo.repofile = mod.configparser.RawConfigParser()
class TemporaryEnvironment(object):
def __init__(self, env=None):
self.original = os.environ.copy()
self.env = env or {}
os.environ.update((k, str(v)) for k, v in self.env.iteritems())
def revert(self):
os.environ.clear()
os.environ.update(self.original)
def run_module(module, raw_params=None, args=None, env=None): def run_module(module, raw_params=None, args=None, env=None):
""" """
Set up the process environment in preparation for running an Ansible Set up the process environment in preparation for running an Ansible
@ -130,25 +141,21 @@ def run_module(module, raw_params=None, args=None, env=None):
'ANSIBLE_MODULE_ARGS': args 'ANSIBLE_MODULE_ARGS': args
}) })
if env: temp_env = TemporaryEnvironment(env)
original_env = os.environ.copy()
os.environ.update((k, str(v)) for k, v in env.iteritems())
try: try:
mod = __import__(module, {}, {}, ['']) try:
module_fixups(mod) mod = __import__(module, {}, {}, [''])
# Ansible modules begin execution on import. Thus the above __import__ module_fixups(mod)
# will cause either Exit or ModuleError to be raised. If we reach the # Ansible modules begin execution on import. Thus the above __import__
# line below, the module did not execute and must already have been # will cause either Exit or ModuleError to be raised. If we reach the
# imported for a previous invocation, so we need to invoke main # line below, the module did not execute and must already have been
# explicitly. # imported for a previous invocation, so we need to invoke main
mod.main() # explicitly.
except (Exit, ModuleError), e: mod.main()
result = json.dumps(e.dct) except (Exit, ModuleError), e:
result = json.dumps(e.dct)
if env: finally:
os.environ.clear() temp_env.revert()
os.environ.update(original_env)
return result return result