from pyexecplugins.pyexecplugins import PyExecPlugin import tempfile import json import logging import subprocess from subprocess import PIPE class Plugin(PyExecPlugin): name = "Packer" taskdef = { "name" : "pypacker", "retryCount" : 0, "description" : "Executes packer.io command line for build and validate. It has been isolated in order to be able to start the worker only where OS dependencies are matched.", "inputKeys" : ["command", "template"], "outputKeys" : ["results"], "ownerEmail" : "m.lettere@gmail.com" } def __init__(self, data=None): super().__init__(data) self.template = data["template"] self.command = data.get("command", "build") self.extra_vars = data.get("extra_vars", {}) def execute(self): fp = tempfile.NamedTemporaryFile(mode="w", delete=False, encoding='utf-8') logging.getLogger("pyexec").debug("Going to %s template %s", self.command, self.data) json.dump(self.template, fp) fp.close() cmd = ["packer", self.command ] for k in self.extra_vars: cmd.append("-var") cmd.append(k + "=" + self.extra_vars.get(k)) cmd.append(fp.name) logging.getLogger("pyexec").debug("Packer command is %s", cmd) try: completed = subprocess.run(cmd, capture_output=True, text=True) except Exception as e: completed = subprocess.run(cmd, stdout=PIPE, stderr=PIPE) logging.getLogger("pyexec").debug("Packer outcome is %s", completed) if(completed.returncode != 0): raise Exception("packer.io failed: {} - out:{} - err:{}".format( completed.returncode, completed.stdout if completed.stdout != None else "", completed.stderr if completed.stderr != None else "") ) return { 'results' : [ { 'returncode' : completed.returncode, 'stdout' : str(completed.stdout), 'stderr': str(completed.stderr) } ] }