From e8eacc98c89937593943ead5fe5d423df58a7826 Mon Sep 17 00:00:00 2001 From: Jan Losinski Date: Fri, 24 May 2019 18:23:13 +0200 Subject: [PATCH] Cache pass calls for a single run. Otherwise it slows down the whole run if the looked up entries are used a lot. Signed-off-by: Jan Losinski --- pass.py | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/pass.py b/pass.py index 16240bc..2dc65a8 100644 --- a/pass.py +++ b/pass.py @@ -26,6 +26,33 @@ from ansible import utils, errors from ansible.plugins.lookup import LookupBase from ansible.errors import AnsibleError + +_cache = {} + + +def _run_cmd(command, basedir, env): + key = hash(command + basedir + str(env)) + if key in _cache: + return _cache[key] + + p = subprocess.Popen(command, + cwd=basedir, + shell=True, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env) + + (stdout, stderr) = p.communicate() + if p.returncode == 0: + data = stdout.decode("utf-8").splitlines()[0].rstrip() + _cache[key] = data + return data + else: + err = stderr.decode("utf-8").rstrip() + raise AnsibleError("lookup_plugin.pass(%s) returned %d: %s" % (term, p.returncode, err)) + + class LookupModule(LookupBase): COMMAND="pass" @@ -78,18 +105,5 @@ class LookupModule(LookupBase): command = "%s %s" % (self.COMMAND, term) - p = subprocess.Popen(command, - cwd=basedir, - shell=True, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - env=env) - - (stdout, stderr) = p.communicate() - if p.returncode == 0: - ret.append(stdout.decode("utf-8").splitlines()[0].rstrip()) - else: - err = stderr.decode("utf-8").rstrip() - raise AnsibleError("lookup_plugin.pass(%s) returned %d: %s" % (term, p.returncode, err)) + ret.append(_run_cmd(command, basedir, env)) return ret