adding caching to script plugin

This commit is contained in:
Brian Coca 2017-05-24 15:08:16 -04:00 committed by Brian Coca
parent b8448fdb90
commit 110fd917d6

View file

@ -82,26 +82,34 @@ class InventoryModule(BaseInventoryPlugin):
# directory when '.' is not in PATH. # directory when '.' is not in PATH.
path = os.path.abspath(path) path = os.path.abspath(path)
cmd = [ path, "--list" ] cmd = [ path, "--list" ]
try: try:
try: cache_key = self.get_cache_prefix(path)
sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if cache and cache_key in inventory.cache:
except OSError as e: data = inventory.cache[cache_key]
raise AnsibleError("problem running %s (%s)" % (' '.join(cmd), e)) else:
(stdout, stderr) = sp.communicate() try:
sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as e:
raise AnsibleError("problem running %s (%s)" % (' '.join(cmd), e))
(stdout, stderr) = sp.communicate()
path = to_native(path) path = to_native(path)
if stderr: if stderr:
err = to_native(stderr) + "\n" err = to_native(stderr) + "\n"
if sp.returncode != 0: if sp.returncode != 0:
raise AnsibleError("Inventory script (%s) had an execution error: %s " % (path, err)) raise AnsibleError("Inventory script (%s) had an execution error: %s " % (path, err))
# make sure script output is unicode so that json loader will output # make sure script output is unicode so that json loader will output
# unicode strings itself # unicode strings itself
try: try:
data = to_text(stdout, errors="strict") data = to_text(stdout, errors="strict")
except Exception as e: except Exception as e:
raise AnsibleError("Inventory {0} contained characters that cannot be interpreted as UTF-8: {1}".format(path, to_native(e))) raise AnsibleError("Inventory {0} contained characters that cannot be interpreted as UTF-8: {1}".format(path, to_native(e)))
if cache:
inventory.cache[cache_key] = data
try: try:
processed = self.loader.load(data) processed = self.loader.load(data)