From acea90ceec4771710af55a1a589ac21cdeaf9281 Mon Sep 17 00:00:00 2001 From: "patchback[bot]" <45432694+patchback[bot]@users.noreply.github.com> Date: Fri, 4 Jun 2021 21:12:50 +0200 Subject: [PATCH] Terraform: ensure workspace is reset to current value (#2634) (#2721) * fix: ensure workspace is reset to current value * chore: linter * chore: changelog (cherry picked from commit c49a384a6522dd9d9b80fd7810df9a8b829e5127) Co-authored-by: christophemorio <49184206+christophemorio@users.noreply.github.com> --- changelogs/fragments/2634-terraform-switch-workspace.yml | 2 ++ plugins/modules/cloud/misc/terraform.py | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/2634-terraform-switch-workspace.yml diff --git a/changelogs/fragments/2634-terraform-switch-workspace.yml b/changelogs/fragments/2634-terraform-switch-workspace.yml new file mode 100644 index 0000000000..247447b3a8 --- /dev/null +++ b/changelogs/fragments/2634-terraform-switch-workspace.yml @@ -0,0 +1,2 @@ +bugfixes: + - terraform - ensure the workspace is set back to its previous value when the apply fails (https://github.com/ansible-collections/community.general/pull/2634). diff --git a/plugins/modules/cloud/misc/terraform.py b/plugins/modules/cloud/misc/terraform.py index f395c8e278..2907016def 100644 --- a/plugins/modules/cloud/misc/terraform.py +++ b/plugins/modules/cloud/misc/terraform.py @@ -398,7 +398,14 @@ def main(): command.append(plan_file) if needs_application and not module.check_mode and not state == 'planned': - rc, out, err = module.run_command(command, check_rc=True, cwd=project_path) + rc, out, err = module.run_command(command, check_rc=False, cwd=project_path) + if rc != 0: + if workspace_ctx["current"] != workspace: + select_workspace(command[0], project_path, workspace_ctx["current"]) + module.fail_json(msg=err.rstrip(), rc=rc, stdout=out, + stdout_lines=out.splitlines(), stderr=err, + stderr_lines=err.splitlines(), + cmd=' '.join(command)) # checks out to decide if changes were made during execution if ' 0 added, 0 changed' not in out and not state == "absent" or ' 0 destroyed' not in out: changed = True