diff --git a/README.rst b/README.rst index ef44faf83d96125b92bd78b5233b0f2087b50620..4f146245c625aa54d1a5ef55a98f2dd77e57da5f 100644 --- a/README.rst +++ b/README.rst @@ -51,6 +51,12 @@ the same name as the workspace, for all the files inside that directory that end with :code:`.tfvars`, a :code:`-var-file` argument is added. For example: :code:`-var-file=prod/a.tfvars` and :code:`-var-file=prod/b.tfvars`. +By default :code:`tf` invokes :code:`terraform`, but if you're using a +different tool (like `OpenTofu <https://opentofu.org/>`_ you can set the +:code:`TF_CLI` environment variable to that tool name. If you wish to know the +exact command :code:`tf` is running set the :code:`TF_DEBUG` environment +variable to :code:`1` and the command will printed before the it's invoked. + License ------- diff --git a/tf.py b/tf.py index 7ecdbd76135f9a7a324ad69cb61a0792bb9a926e..19bceb950d5ec0694bc104178a64d8d44411fba2 100644 --- a/tf.py +++ b/tf.py @@ -8,19 +8,24 @@ import pathlib import subprocess # nosec import sys -__version__ = "0.1.0" +__version__ = "0.2.0" TF_COMMANDS_TO_MODIFY = ["plan", "console", "import", "refresh"] +TF_CLI = os.getenv("TF_CLI", "terraform") def get_workspace(): """Return the Terraform workspace.""" - proc = subprocess.run( # nosec - ["terraform", "workspace", "show"], - capture_output=True, - check=True, - text=True, - ) + try: + proc = subprocess.run( # nosec + [TF_CLI, "workspace", "show"], + capture_output=True, + check=True, + text=True, + ) + except FileNotFoundError: + print(f"Can't find {TF_CLI}.", file=sys.stderr) + sys.exit(1) return proc.stdout.strip() @@ -33,11 +38,15 @@ def is_debug_set(): def wrapper(): # In case tf was run with no arguments. if len(sys.argv) == 1: - os.execlp("terraform", "terraform") # nosec + try: + os.execlp(TF_CLI, TF_CLI) # nosec + except FileNotFoundError: + print(f"Can't find {TF_CLI}.", file=sys.stderr) + sys.exit(1) # Build a new argument list. args = sys.argv[:] - args[0] = "terraform" + args[0] = TF_CLI # Check if the Terraform command is one that we need to modify (include # tfvars files). If not, execute Terraform with the same arguments. @@ -45,7 +54,11 @@ def wrapper(): if command in sys.argv: break else: - os.execvp("terraform", args) # nosec + try: + os.execvp(TF_CLI, args) # nosec + except FileNotFoundError: + print(f"Can't find {TF_CLI}.", file=sys.stderr) + sys.exit(1) # 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 @@ -65,7 +78,11 @@ def wrapper(): if is_debug_set(): print(args, file=sys.stderr) - os.execvp("terraform", args) # nosec + try: + os.execvp(TF_CLI, args) # nosec + except FileNotFoundError: + print(f"Can't find {TF_CLI}.", file=sys.stderr) + sys.exit(1) if __name__ == "__main__":