From 9eba26a3e8840760293acc49b1c4cf96c222486c Mon Sep 17 00:00:00 2001
From: Adar Nimrod <nimrod@shore.co.il>
Date: Sun, 14 Aug 2022 12:58:23 +0300
Subject: [PATCH] Rewrite tf in Python.

There's an issue with tf import because the options (-var-file=...) must
precede the other arguments (resource name and ID). Writing it in POSIX
shell without arrays is going to be a mess. I can probably write it in
Bash but I prefer Python so here we are. I also feel it's a bit more
readable.
---
 Documents/bin/tf | 70 +++++++++++++++++++++++++++++-------------------
 1 file changed, 43 insertions(+), 27 deletions(-)

diff --git a/Documents/bin/tf b/Documents/bin/tf
index 070c7db..5ed12a9 100755
--- a/Documents/bin/tf
+++ b/Documents/bin/tf
@@ -1,31 +1,47 @@
-#!/bin/sh
-set -eu
+#!/usr/bin/env python3
+"""Terraform wrapper to include a variable file is one exists that matches the workspace name"""  # noqa: E501
 
-# A wrapper for Terraform to include a variables file if one exists that matches
-# the workspace name (on commands that support that).
+import glob
+import os
+import pathlib
+import subprocess  # nosec
+import sys
 
-workspace="$(terraform workspace show)"
-if [ ! -f "$workspace.tfvars" ] && [ ! -d "$workspace" ]
-then
-    exec terraform "$@"
-fi
+TF_COMMANDS_TO_MODIFY = ["plan", "console", "import", "refresh"]
 
-for arg in "$@"
-do
-    if [ "$arg" = "plan" ] || [ "$arg" = "console" ] || [ "$arg" = "import" ] ||
-        [ "$arg" = "refresh" ]
-    then
-        additional_args=''
-        if [ -f "$workspace.tfvars" ]
-        then
-            additional_args="$additional_args -var-file=$workspace.tfvars"
-        fi
-        if [ -d "$workspace" ]
-        then
-            additional_args="$additional_args $(find "$workspace" -type f -name '*.tfvars' -exec printf '-var-file=%s ' {} \;)"
-        fi
-    fi
-done
 
-# shellcheck disable=SC2086
-exec terraform "$@" ${additional_args:-}
+def get_workspace():
+    """Return the Terraform workspace."""
+    proc = subprocess.run(  # nosec
+        ["terraform", "workspace", "show"],
+        capture_output=True,
+        check=True,
+        text=True,
+    )
+    return proc.stdout.strip()
+
+
+if __name__ == "__main__":
+    if len(sys.argv) == 1:
+        os.execlp("terraform", "terraform")  # nosec
+    for command in TF_COMMANDS_TO_MODIFY:
+        if command in sys.argv:
+            break
+    else:
+        args = sys.argv[:]
+        args[0] = "terraform"
+        os.execvp("terraform", args)  # nosec
+
+    args = sys.argv[:]
+    args[0] = "terraform"
+    command_index = args.index(command)
+    workspace = get_workspace()
+    var_file = pathlib.Path(f"{workspace}.tfvars")
+    var_dir = pathlib.Path(workspace)
+    if var_file.exists() and var_file.is_file():
+        args.insert(command_index + 1, f"-var-file={var_file}")
+    elif var_dir.exists() and var_dir.is_dir():
+        for var_file in glob.glob(f"{var_dir}/*.tfvars"):
+            args.insert(command_index + 1, f"-var-file={var_file}")
+    print(args, file=sys.stderr)
+    os.execvp("terraform", args)  # nosec
-- 
GitLab