From ce122cbd6a990365d7dc3da6b90be431d01ed7aa Mon Sep 17 00:00:00 2001
From: Adar Nimrod <nimrod@shore.co.il>
Date: Sun, 24 Dec 2023 18:51:33 +0200
Subject: [PATCH] Terraform stuff.

- Remove the tf wrapper, use the version from PyPI.
- Move all of the Terraform stuff to ~/.bashrc.d/ .
- Use OpenTofu instead of Terraform with tf.
- Refresh the outputs after an apply.
---
 .bashrc             |  5 ----
 .bashrc.d/terraform |  9 +++++++
 Documents/bin/tf    | 66 ---------------------------------------------
 3 files changed, 9 insertions(+), 71 deletions(-)
 create mode 100644 .bashrc.d/terraform
 delete mode 100755 Documents/bin/tf

diff --git a/.bashrc b/.bashrc
index 7271939..246f517 100644
--- a/.bashrc
+++ b/.bashrc
@@ -82,7 +82,6 @@ export PS1='\u@\h:\w\$ '
 export PYTHONSTARTUP=~/.config/pythonrc.py
 export PYTHON_GITLAB_CFG=~/.config/python-gitlab.cfg
 export REDISCLI_HISTFILE="$HOME/Documents/.rediscli_history"
-export TF_DEBUG=1
 export VAGRANT_DEFAULT_PROVIDER="virtualbox"
 
 alias 0-day-cleanup='ssh kodi.shore.co.il "sudo -u debian-transmission find /srv/library/Comics -name *.part -path *0-Day\ Week\ of* -delete"'
@@ -177,10 +176,6 @@ alias screenshot-cleanup='find "$HOME/Pictures" -name "Screenshot from *.png" -d
 alias smtp-server='python3 -m smtpd -ndc DebuggingServer'
 alias sudo="sudo "
 alias sudome="sudome "
-alias tfa='tf apply tfplan'
-alias tfaa='tf apply -auto-approve'
-alias tfp='tf init -backend=false && tf plan -out tfplan'
-alias tfvf='tf init -backend=false && tf validate && tf fmt -diff'
 alias todo="vim \$HOME/Documents/TODO.yml"
 # shellcheck disable=SC2142
 alias tolower='awk "{print tolower(\$0)}"'
diff --git a/.bashrc.d/terraform b/.bashrc.d/terraform
new file mode 100644
index 0000000..96a0de7
--- /dev/null
+++ b/.bashrc.d/terraform
@@ -0,0 +1,9 @@
+# shellcheck shell=bash
+# vim: ft=sh
+
+export TF_CLI=tofu
+export TF_DEBUG=1
+alias tfa='tf apply tfplan && tf -auto-approve -refresh-only'
+alias tfaa='tf apply -auto-approve'
+alias tfp='tf init -backend=false && tf plan -out tfplan'
+alias tfvf='tf init -backend=false && tf validate && tf fmt -diff'
diff --git a/Documents/bin/tf b/Documents/bin/tf
deleted file mode 100755
index 7812aed..0000000
--- a/Documents/bin/tf
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env python3
-"""Terraform wrapper to include variable files if they match the workspace
-name."""
-
-import glob
-import os
-import pathlib
-import subprocess  # nosec
-import sys
-
-TF_COMMANDS_TO_MODIFY = ["plan", "console", "import", "refresh"]
-
-
-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()
-
-
-def is_debug_set():
-    """Check if the debug environment variable is set."""
-    debug = os.getenv("TF_DEBUG", "").lower()
-    return debug in ["1", "true"]
-
-
-if __name__ == "__main__":
-    # In case tf was run with no arguments.
-    if len(sys.argv) == 1:
-        os.execlp("terraform", "terraform")  # nosec
-
-    # Build a new argument list.
-    args = sys.argv[:]
-    args[0] = "terraform"
-
-    # Check if the Terraform command is one that we need to modify (include
-    # tfvars files). If not, execute Terraform with the same arguments.
-    for command in TF_COMMANDS_TO_MODIFY:
-        if command in sys.argv:
-            break
-    else:
-        os.execvp("terraform", args)  # nosec
-
-    # We need to add the var files after the Terraform command (if we add it
-    # before Terraform doesn't accept them) but not at the end (not to modify
-    # other argument that accept optional values). So we add them right after
-    # the Terraform command.
-    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 the new argument list to stderr if debugging is enabled.
-    if is_debug_set():
-        print(args, file=sys.stderr)
-
-    os.execvp("terraform", args)  # nosec
-- 
GitLab