Skip to content
This repository has been archived by the owner on Jan 6, 2023. It is now read-only.

molecule_vagrant/modules/vagrant.py: Improve error handling #80

Merged
merged 1 commit into from
Nov 4, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 28 additions & 17 deletions molecule_vagrant/modules/vagrant.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,17 +448,17 @@ def up(self):
# passes the actual error as a no-argument ContextManager.
pass

# NOTE(retr0h): Ansible wants only one module return `fail_json`
# or `exit_json`.
if not self._has_error:
self._module.exit_json(
changed=changed, log=self._get_stdout_log(), **self._conf()
)
else:
msg = "ERROR: See log file '{}'".format(self._get_stderr_log())
with io.open(self._get_stderr_log(), "r", encoding="utf-8") as f:
self.result["stderr"] = f.read()
self._module.fail_json(msg=msg, **self.result)
# NOTE(retr0h): Ansible wants only one module return `fail_json`
# or `exit_json`.
if not self._has_error:
self._module.exit_json(
changed=changed, log=self._get_stdout_log(), **self._conf()
)

msg = "Failed to start the VM: See log file '{}'".format(self._get_stderr_log())
with io.open(self._get_stderr_log(), "r", encoding="utf-8") as f:
self.result["stderr"] = f.read()
self._module.fail_json(msg=msg, **self.result)

def destroy(self):
changed = False
Expand All @@ -481,18 +481,29 @@ def halt(self):
def _conf(self):
instance_name = self._module.params["instance_name"]

return self._vagrant.conf(vm_name=instance_name)
try:
return self._vagrant.conf(vm_name=instance_name)
except Exception:
msg = "Failed to get vagrant config for {}: See log file '{}'".format(
instance_name, self._get_stderr_log()
)
with io.open(self._get_stderr_log(), "r", encoding="utf-8") as f:
self.result["stderr"] = f.read()
self._module.fail_json(msg=msg, **self.result)

def _status(self):
instance_name = self._module.params["instance_name"]
try:
s = self._vagrant.status(vm_name=instance_name)[0]

return {"name": s.name, "state": s.state, "provider": s.provider}
except AttributeError:
pass
except subprocess.CalledProcessError:
pass
except Exception:
msg = "Failed to get status for {}: See log file '{}'".format(
instance_name, self._get_stderr_log()
)
with io.open(self._get_stderr_log(), "r", encoding="utf-8") as f:
self.result["stderr"] = f.read()
self._module.fail_json(msg=msg, **self.result)

def _created(self):
status = self._status()
Expand Down Expand Up @@ -632,7 +643,7 @@ def main():
if module.params["state"] == "halt":
v.halt()

module.exit_json(**module.result)
module.fail_json(msg="Unknown error", **v.result)


if __name__ == "__main__":
Expand Down