Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support set custom TF/OpenTofu binary. | If you use a custom Docker image build, please note that TERRAFORM_VERSION now must be provided #670

Merged
merged 36 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
c85dfd5
Allowing setting custom TF binary
den-is May 4, 2024
30674bc
README update
den-is May 4, 2024
af193f1
Update README.md
den-is May 9, 2024
43edcea
Update README.md
den-is May 9, 2024
78f7f10
Update hooks/_common.sh
den-is May 9, 2024
45706a8
Update hooks/_common.sh
den-is May 9, 2024
4018878
Update hooks/_common.sh
den-is May 9, 2024
c25e0fb
Update hooks/_common.sh
den-is May 9, 2024
7c448a6
Update hooks/_common.sh
den-is May 9, 2024
b1dd3bb
Update hooks/_common.sh
den-is May 9, 2024
2e353ba
refactoring
den-is May 9, 2024
8ca6f2d
update terraform_providers_lock.sh
den-is May 9, 2024
d3c85b4
README update
den-is May 9, 2024
c73c2e8
add globals doc for common::get_tf_path
den-is May 9, 2024
5301302
centralize TF_PATH initialization
den-is May 9, 2024
53146fe
fix expected hook-config arg
den-is May 9, 2024
a6fedca
fix command checks
den-is May 9, 2024
2f6f7b0
README update
den-is May 11, 2024
200b96b
README update
den-is May 11, 2024
5091208
README update
den-is May 11, 2024
3f94d4f
README update
den-is May 11, 2024
741aac6
README update
den-is May 11, 2024
128d4fa
README update
den-is May 11, 2024
c20b5fd
Apply suggestions from code review
MaxymVlasov May 21, 2024
e7deaaf
Apply suggestions from code review
MaxymVlasov May 21, 2024
e771a4f
Update README.md
den-is May 21, 2024
258234f
README update
den-is May 21, 2024
3660e75
Discard changes to README.md
MaxymVlasov May 21, 2024
6670e51
Revert "Discard changes to README.md"
MaxymVlasov May 21, 2024
825b7f0
Revert "README update"
MaxymVlasov May 21, 2024
bc2766c
Switch from global env to local in-function constant
MaxymVlasov May 21, 2024
168dd6a
fixup. Useless suppresions
MaxymVlasov May 21, 2024
80d239d
Add tofu to Docker, make terraform and tofu non-required deps
MaxymVlasov May 21, 2024
c7ad7d1
Add tofu to ISSUE template
MaxymVlasov May 21, 2024
e3c66bd
Apply suggestions from code review
MaxymVlasov May 22, 2024
1cb551e
Extract only need binary file
MaxymVlasov May 22, 2024
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
159 changes: 85 additions & 74 deletions README.md
den-is marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -25,69 +25,80 @@ If you are using `pre-commit-terraform` already or want to support its developme

## Table of content

* [Sponsors](#sponsors)
* [Table of content](#table-of-content)
* [How to install](#how-to-install)
* [1. Install dependencies](#1-install-dependencies)
* [2. Install the pre-commit hook globally](#2-install-the-pre-commit-hook-globally)
* [3. Add configs and hooks](#3-add-configs-and-hooks)
* [4. Run](#4-run)
* [Available Hooks](#available-hooks)
* [Hooks usage notes and examples](#hooks-usage-notes-and-examples)
* [Known limitations](#known-limitations)
* [All hooks: Usage of environment variables in `--args`](#all-hooks-usage-of-environment-variables-in---args)
* [All hooks: Set env vars inside hook at runtime](#all-hooks-set-env-vars-inside-hook-at-runtime)
* [All hooks: Disable color output](#all-hooks-disable-color-output)
* [All hooks: Log levels](#all-hooks-log-levels)
* [Many hooks: Parallelism](#many-hooks-parallelism)
* [checkov (deprecated) and terraform\_checkov](#checkov-deprecated-and-terraform_checkov)
* [infracost\_breakdown](#infracost_breakdown)
* [terraform\_docs](#terraform_docs)
* [terraform\_docs\_replace (deprecated)](#terraform_docs_replace-deprecated)
* [terraform\_fmt](#terraform_fmt)
* [terraform\_providers\_lock](#terraform_providers_lock)
* [terraform\_tflint](#terraform_tflint)
* [terraform\_tfsec (deprecated)](#terraform_tfsec-deprecated)
* [terraform\_trivy](#terraform_trivy)
* [terraform\_validate](#terraform_validate)
* [terraform\_wrapper\_module\_for\_each](#terraform_wrapper_module_for_each)
* [terrascan](#terrascan)
* [tfupdate](#tfupdate)
* [terragrunt\_providers\_lock](#terragrunt_providers_lock)
* [Docker Usage](#docker-usage)
* [File Permissions](#file-permissions)
* [Download Terraform modules from private GitHub repositories](#download-terraform-modules-from-private-github-repositories)
* [Github Actions](#github-actions)
* [Authors](#authors)
* [License](#license)
* [Additional information for users from Russia and Belarus](#additional-information-for-users-from-russia-and-belarus)
- [Collection of git hooks for Terraform to be used with pre-commit framework](#collection-of-git-hooks-for-terraform-to-be-used-with-pre-commit-framework)
- [Sponsors](#sponsors)
- [Table of content](#table-of-content)
- [How to install](#how-to-install)
- [1. Install dependencies](#1-install-dependencies)
- [1.1 Custom Terraform binaries and OpenTofu support](#11-custom-terraform-binaries-and-opentofu-support)
- [2. Install the pre-commit hook globally](#2-install-the-pre-commit-hook-globally)
- [3. Add configs and hooks](#3-add-configs-and-hooks)
- [4. Run](#4-run)
- [Available Hooks](#available-hooks)
- [Hooks usage notes and examples](#hooks-usage-notes-and-examples)
- [Known limitations](#known-limitations)
- [All hooks: Usage of environment variables in `--args`](#all-hooks-usage-of-environment-variables-in---args)
- [All hooks: Set env vars inside hook at runtime](#all-hooks-set-env-vars-inside-hook-at-runtime)
- [All hooks: Disable color output](#all-hooks-disable-color-output)
- [All hooks: Log levels](#all-hooks-log-levels)
- [Many hooks: Parallelism](#many-hooks-parallelism)
- [checkov (deprecated) and terraform\_checkov](#checkov-deprecated-and-terraform_checkov)
- [infracost\_breakdown](#infracost_breakdown)
- [terraform\_docs](#terraform_docs)
- [terraform\_docs\_replace (deprecated)](#terraform_docs_replace-deprecated)
- [terraform\_fmt](#terraform_fmt)
- [terraform\_providers\_lock](#terraform_providers_lock)
- [terraform\_tflint](#terraform_tflint)
- [terraform\_tfsec (deprecated)](#terraform_tfsec-deprecated)
- [terraform\_trivy](#terraform_trivy)
- [terraform\_validate](#terraform_validate)
- [terraform\_wrapper\_module\_for\_each](#terraform_wrapper_module_for_each)
- [terrascan](#terrascan)
- [tfupdate](#tfupdate)
- [terragrunt\_providers\_lock](#terragrunt_providers_lock)
- [Docker Usage](#docker-usage)
- [File Permissions](#file-permissions)
- [Download Terraform modules from private GitHub repositories](#download-terraform-modules-from-private-github-repositories)
- [Github Actions](#github-actions)
- [Authors](#authors)
- [License](#license)
- [Additional information for users from Russia and Belarus](#additional-information-for-users-from-russia-and-belarus)

## How to install

### 1. Install dependencies

* [`pre-commit`](https://pre-commit.com/#install),
<sub><sup>[`terraform`](https://www.terraform.io/downloads.html),
den-is marked this conversation as resolved.
Show resolved Hide resolved
<sub><sup>[`git`](https://git-scm.com/downloads),
<sub><sup>[BASH `3.2.57` or newer](https://www.gnu.org/software/bash/#download),
<sub><sup>Internet connection (on first run),
<sub><sup>x86_64 or arm64 compatible operation system,
<sub><sup>Some hardware where this OS will run,
<sub><sup>Electricity for hardware and internet connection,
<sub><sup>Some basic physical laws,
<sub><sup>Hope that it all will work.
</sup></sub></sup></sub></sup></sub></sup></sub></sup></sub></sup></sub></sup></sub></sup></sub></sup></sub><br><br>
* [`checkov`](https://github.com/bridgecrewio/checkov) required for `terraform_checkov` hook.
* [`terraform-docs`](https://github.com/terraform-docs/terraform-docs) required for `terraform_docs` hook.
* [`terragrunt`](https://terragrunt.gruntwork.io/docs/getting-started/install/) required for `terragrunt_validate` hook.
* [`terrascan`](https://github.com/tenable/terrascan) required for `terrascan` hook.
* [`TFLint`](https://github.com/terraform-linters/tflint) required for `terraform_tflint` hook.
* [`TFSec`](https://github.com/liamg/tfsec) required for `terraform_tfsec` hook.
* [`Trivy`](https://github.com/aquasecurity/trivy) required for `terraform_trivy` hook.
* [`infracost`](https://github.com/infracost/infracost) required for `infracost_breakdown` hook.
* [`jq`](https://github.com/stedolan/jq) required for `terraform_validate` with `--retry-once-with-cleanup` flag, and for `infracost_breakdown` hook.
* [`tfupdate`](https://github.com/minamijoyo/tfupdate) required for `tfupdate` hook.
* [`hcledit`](https://github.com/minamijoyo/hcledit) required for `terraform_wrapper_module_for_each` hook.
- [`pre-commit`](https://pre-commit.com/#install)
- [`terraform`](https://www.terraform.io/downloads.html) and/or [`OpenTofu`](https://opentofu.org/docs/intro/install/)
- [`git`](https://git-scm.com/downloads)
- [BASH `3.2.57` or newer](https://www.gnu.org/software/bash/#download)
- Internet connection (on first run)
- x86_64 or arm64 compatible operation system
- [`checkov`](https://github.com/bridgecrewio/checkov) required for `terraform_checkov` hook
- [`terraform-docs`](https://github.com/terraform-docs/terraform-docs) required for `terraform_docs` hook
- [`terragrunt`](https://terragrunt.gruntwork.io/docs/getting-started/install/) required for `terragrunt_validate` hook
- [`terrascan`](https://github.com/tenable/terrascan) required for `terrascan` hook
- [`TFLint`](https://github.com/terraform-linters/tflint) required for `terraform_tflint` hook
- [`TFSec`](https://github.com/liamg/tfsec) required for `terraform_tfsec` hook
- [`Trivy`](https://github.com/aquasecurity/trivy) required for `terraform_trivy` hook
- [`infracost`](https://github.com/infracost/infracost) required for `infracost_breakdown` hook
- [`jq`](https://github.com/stedolan/jq) required for `terraform_validate` with `--retry-once-with-cleanup` flag, and for `infracost_breakdown` hook
- [`tfupdate`](https://github.com/minamijoyo/tfupdate) required for `tfupdate` hook
- [`hcledit`](https://github.com/minamijoyo/hcledit) required for `terraform_wrapper_module_for_each` hook

#### 1.1 Custom Terraform binaries and OpenTofu support

It is possible to set custom path to `terraform` binary.

This makes it possible to use [OpenTofu](https://opentofu.org) binary `tofu` instead of `terraform`.

How to:

- For per hook configuration set `--hook-config=--tf-path=<path_to_binary_or_binary_name>`
- export `PCT_TFPATH=<path_to_binary_or_binary_name>` environment variable
- or maybe your already have `TERRAGRUNT_TFPATH=<path_to_binary_or_binary_name>` environment variable set
- if none of above is set/available, hook defaults to `terraform` binary found in the user's $PATH
- if none of above are set/available, hook try to find and use `tofu` binary in the user's $PATH

<details><summary><b>Docker</b></summary><br>

Expand All @@ -103,7 +114,7 @@ All available tags [here](https://github.com/antonbabenko/pre-commit-terraform/p
**Build from scratch**:

> [!IMPORTANT]
> To build image you need to have [`docker buildx`](https://docs.docker.com/build/install-buildx/) enabled as default builder.
> To build image you need to have [`docker buildx`](https://docs.docker.com/build/install-buildx/) enabled as default builder.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please put two trailing spaces back — they denote carriage return in markdown.
Same applies to the similar changes across this file in the PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was fixed by VSCode automatically.
Will check for workaround

> Otherwise - provide `TARGETOS` and `TARGETARCH` as additional `--build-arg`'s to `docker build`.

When hooks-related `--build-arg`s are not specified, only the latest version of `pre-commit` and `terraform` will be installed.
Expand Down Expand Up @@ -208,7 +219,7 @@ Otherwise, you can follow [this gist](https://gist.github.com/etiennejeanneaurev

Ensure your PATH environment variable looks for `bash.exe` in `C:\Program Files\Git\bin` (the one present in `C:\Windows\System32\bash.exe` does not work with `pre-commit.exe`)

For `checkov`, you may need to also set your `PYTHONPATH` environment variable with the path to your Python modules.
For `checkov`, you may need to also set your `PYTHONPATH` environment variable with the path to your Python modules.
E.g. `C:\Users\USERNAME\AppData\Local\Programs\Python\Python39\Lib\site-packages`

</details>
Expand Down Expand Up @@ -361,10 +372,10 @@ Less verbose log levels will be implemented in [#562](https://github.com/antonba

### Many hooks: Parallelism

> All, except deprecated hooks: `checkov`, `terraform_docs_replace` and hooks which can't be paralleled this way: `infracost_breakdown`, `terraform_wrapper_module_for_each`.
> All, except deprecated hooks: `checkov`, `terraform_docs_replace` and hooks which can't be paralleled this way: `infracost_breakdown`, `terraform_wrapper_module_for_each`.
> Also, there's a chance that parallelism have no effect on `terragrunt_fmt` and `terragrunt_validate` hooks

By default, parallelism is set to `number of logical CPUs - 1`.
By default, parallelism is set to `number of logical CPUs - 1`.
If you'd like to disable parallelism, set it to `1`

```yaml
Expand Down Expand Up @@ -420,7 +431,7 @@ args:
- --hook-config=--parallelism-ci-cpu-cores=N
```

If you don't see code above in your `pre-commit-config.yaml` or logs - you don't need it.
If you don't see code above in your `pre-commit-config.yaml` or logs - you don't need it.
`--parallelism-ci-cpu-cores` used only in edge cases and is ignored in other situations. Check out its usage in [hooks/_common.sh](hooks/_common.sh)

### checkov (deprecated) and terraform_checkov
Expand Down Expand Up @@ -568,7 +579,7 @@ Unlike most other hooks, this hook triggers once if there are any changed files
* create a documentation file
* extend existing documentation file by appending markers to the end of the file (see item 1 above)
* use different filename for the documentation (default is `README.md`)
* use the same insertion markers as `terraform-docs` by default. It will be default in `v2.0`.
* use the same insertion markers as `terraform-docs` by default. It will be default in `v2.0`.
To migrate to `terraform-docs` insertion markers, run in repo root:

```bash
Expand All @@ -593,7 +604,7 @@ Unlike most other hooks, this hook triggers once if there are any changed files
- --args=--config=.terraform-docs.yml
```

> **Warning**
> **Warning**
> Avoid use `recursive.enabled: true` in config file, that can cause unexpected behavior.

5. If you need some exotic settings, it can be done too. I.e. this one generates HCL files:
Expand Down Expand Up @@ -744,7 +755,7 @@ To replicate functionality in `terraform_docs` hook:

3. `terraform_providers_lock` support passing custom arguments to its `terraform init`:

> **Warning**
> **Warning**
> DEPRECATION NOTICE: This is available only in `no-mode` mode, which will be removed in v2.0. Please provide this keys to [`terraform_validate`](#terraform_validate) hook, which, to take effect, should be called before `terraform_providers_lock`

```yaml
Expand Down Expand Up @@ -925,10 +936,10 @@ To replicate functionality in `terraform_docs` hook:
- --hook-config=--retry-once-with-cleanup=true # Boolean. true or false
```

> **Important**
> **Important**
> The flag requires additional dependency to be installed: `jq`.

> **Note**
> **Note**
> Reinit can be very slow and require downloading data from remote Terraform registries, and not all of that downloaded data or meta-data is currently being cached by Terraform.

When `--retry-once-with-cleanup=true`, in each failed directory the cached modules and providers from the `.terraform` directory will be deleted, before retrying once more. To avoid unnecessary deletion of this directory, the cleanup and retry will only happen if Terraform produces any of the following error messages:
Expand All @@ -939,7 +950,7 @@ To replicate functionality in `terraform_docs` hook:
* "Module not installed"
* "Could not load plugin"

> **Warning**
> **Warning**
> When using `--retry-once-with-cleanup=true`, problematic `.terraform/modules/` and `.terraform/providers/` directories will be recursively deleted without prompting for consent. Other files and directories will not be affected, such as the `.terraform/environment` file.

**Option 2**
Expand All @@ -958,7 +969,7 @@ To replicate functionality in `terraform_docs` hook:

`terraform_validate` hook will try to reinitialize them before running the `terraform validate` command.

> **Caution**
> **Caution**
> If you use Terraform workspaces, DO NOT use this option ([details](https://github.com/antonbabenko/pre-commit-terraform/issues/203#issuecomment-918791847)). Consider the first option, or wait for [`force-init`](https://github.com/antonbabenko/pre-commit-terraform/issues/224) option implementation.

1. `terraform_validate` in a repo with Terraform module, written using Terraform 0.15+ and which uses provider `configuration_aliases` ([Provider Aliases Within Modules](https://www.terraform.io/language/modules/develop/providers#provider-aliases-within-modules)), errors out.
Expand Down Expand Up @@ -1010,7 +1021,7 @@ To replicate functionality in `terraform_docs` hook:
[...]
```

> **Tip**
> **Tip**
> The latter method will leave an "aliased-providers.tf.json" file in your repo. You will either want to automate a way to clean this up or add it to your `.gitignore` or both.

### terraform_wrapper_module_for_each
Expand All @@ -1034,8 +1045,8 @@ Sample configuration:
- --args=--verbose # Verbose output
```

**If you use hook inside Docker:**
The `terraform_wrapper_module_for_each` hook attempts to determine the module's short name to be inserted into the generated `README.md` files for the `source` URLs. Since the container uses a bind mount at a static location, it can cause this short name to be incorrect.
**If you use hook inside Docker:**
The `terraform_wrapper_module_for_each` hook attempts to determine the module's short name to be inserted into the generated `README.md` files for the `source` URLs. Since the container uses a bind mount at a static location, it can cause this short name to be incorrect.
If the generated name is incorrect, set them by providing the `module-repo-shortname` option to the hook:

```yaml
Expand Down Expand Up @@ -1085,7 +1096,7 @@ If the generated name is incorrect, set them by providing the `module-repo-short
- --args=--version 2.5.0 # Will be pined to specified version
```

Check [`tfupdate` usage instructions](https://github.com/minamijoyo/tfupdate#usage) for other available options and usage examples.
Check [`tfupdate` usage instructions](https://github.com/minamijoyo/tfupdate#usage) for other available options and usage examples.
No need to pass `--recursive .` as it is added automatically.

### terragrunt_providers_lock
Expand Down
60 changes: 58 additions & 2 deletions hooks/_common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,9 @@ function common::per_dir_hook {
# despite there's only one positional ARG left
local -a -r files=("$@")

# shellcheck disable=SC2155
export TF_PATH=$(common::get_tf_path)
MaxymVlasov marked this conversation as resolved.
Show resolved Hide resolved

# check is (optional) function defined
if [ "$(type -t run_hook_on_whole_repo)" == function ] &&
# check is hook run via `pre-commit run --all`
Expand Down Expand Up @@ -445,6 +448,57 @@ function common::colorify {
echo -e "${COLOR}${TEXT}${RESET}" >&2
}

#######################################################################
# Set Terraform/OpenTofu binary path
# Allows user to set the path to custom Terraform or OpenTofu binary
# Globals (init and populate):
# HOOK_CONFIG (array) arguments that configure hook behavior
# PCT_TFPATH (string) user defined env var with path to Terraform/OpenTofu binary
# TERRAGRUNT_TFPATH (string) user defined env var with path to Terraform/OpenTofu binary
# Outputs:
# If failed - exit 1 with error message about missing Terraform/OpenTofu binary
function common::get_tf_path {
MaxymVlasov marked this conversation as resolved.
Show resolved Hide resolved
local hook_config_tf_path

for config in "${HOOK_CONFIG[@]}"; do
if [[ $config == --tf_path=* ]]; then
hook_config_tf_path=${config#*=}
hook_config_tf_path=${hook_config_tf_path%;}
den-is marked this conversation as resolved.
Show resolved Hide resolved
break
fi
done

# direct hook config, has the highest precedence
if [[ $hook_config_tf_path ]]; then
echo "${hook_config_tf_path}"
MaxymVlasov marked this conversation as resolved.
Show resolved Hide resolved
return

# environment variable
elif [[ $PCT_TFPATH ]]; then
echo "${PCT_TFPATH}"
MaxymVlasov marked this conversation as resolved.
Show resolved Hide resolved
return

# Maybe there is a similar setting for Terragrunt already
elif [[ $TERRAGRUNT_TFPATH ]]; then
echo "${TERRAGRUNT_TFPATH}"
MaxymVlasov marked this conversation as resolved.
Show resolved Hide resolved
return
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't get it

According to https://terragrunt.gruntwork.io/docs/reference/cli-options/#terragrunt-tfpath it will be automatically specified for terragrunt => for terragrunt hooks too.

Why do we need to set Terragrunt path for vanilla TF hooks?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Imagine you are working in some environment that already uses TERRAGRUNT_TFPATH env variable (global env, using direnv, or any other method)
So if a variable already exists and serves exactly the same purposes, why not to check it and reuse it, why to have other args/vars/etc?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I'm following the gist of the question, though probably (I'm purely guesstimating) this way it would be easier for people using both TF and TG hooks to specify custom binary only once using TG's method but covering also TF? 🤔 And from this point of view it makes sense to me.

@den-is What's your idea?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I'm following the gist of the question, though probably (I'm purely guesstimating) this way it would be easier for people using both TF and TG hooks to specify custom binary only once using TG's method but covering also TF? 🤔 And from this point of view it makes sense to me.

@yermulnik Erm... this was already replied to by me yesterday.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Folks that use terragrunt should use terragrunt hooks, not terraform hooks - terraform will just not work in most cases. It's hard to imagine that someone uses both terragrunt and vanilla terraform, but if so - why do we think that folks would be happy with interference between "prj1 with TG and OpenTofu" and "prj2 with vanilla TF"?

And another question: do we need to specify $tf_path for terragrunt hooks?

Like terragrunt validate --terragrunt-tfpath "$tf_path" "${args[@]}"

terragrunt validate "${args[@]}"

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Erm... this was already replied to by me yesterday.

@den-is My bad. I missed that comment (found it now). Thanks.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's hard to imagine that someone uses both terragrunt and vanilla terraform

I don't in particular, but a fellow squad in my project — does. And I'd imagine there are people in the wild who do the same and hence they may like using TERRAGRUNT_TFPATH to cover both use cases if they use pre-commit-terraform.

And another question: do we need to specify $tf_path for terragrunt hooks?

That's a good question. We probably should. But only when it is provided via TG hook config. In the rest of use cases TG should rely upon its own logic, including TERRAGRUNT_TFPATH and others described at https://terragrunt.gruntwork.io/docs/reference/cli-options/#terragrunt-tfpath

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had a conversation with @den-is
TL;DR: we assume that it will no break anything in 99% of cases. And if such a thing happened - I'll mention Den is such an issue :D

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Works for me 👍🏻

I'll mention Den is such an issue :D

I feel like is should be in, but with is the sentence sounds fabulous 🤣


# check if Terraform binary is available
elif command -v terraform &>/dev/null; then
command -v terraform
return

# finally, check if Tofu binary is available
elif command -v tofu >/dev/null 2>&1; then
command -v tofu
return

else
common::colorify "red" "Neither Terraform nor OpenTofu binary could be found. Please either set the \"--tf-path\" hook configuration argument, or set the \"PCT_TFPATH\" environment variable, or set the \"TERRAGRUNT_TFPATH\" environment variable, or install Terraform or OpenTofu globally."
exit 1
yermulnik marked this conversation as resolved.
Show resolved Hide resolved
fi
}

#######################################################################
# Run terraform init command
# Arguments:
Expand All @@ -468,6 +522,8 @@ function common::terraform_init {
local exit_code=0
local init_output

TF_PATH=$(common::get_tf_path)

MaxymVlasov marked this conversation as resolved.
Show resolved Hide resolved
# Suppress terraform init color
if [ "$PRE_COMMIT_COLOR" = "never" ]; then
TF_INIT_ARGS+=("-no-color")
Expand All @@ -480,13 +536,13 @@ function common::terraform_init {
# Plugin cache dir can't be written concurrently or read during write
# https://github.com/hashicorp/terraform/issues/31964
if [[ -z $TF_PLUGIN_CACHE_DIR || $parallelism_disabled == true ]]; then
init_output=$(terraform init -backend=false "${TF_INIT_ARGS[@]}" 2>&1)
init_output=$($TF_PATH init -backend=false "${TF_INIT_ARGS[@]}" 2>&1)
exit_code=$?
else
# Locking just doesn't work, and the below works quicker instead. Details:
# https://github.com/hashicorp/terraform/issues/31964#issuecomment-1939869453
for i in {1..10}; do
init_output=$(terraform init -backend=false "${TF_INIT_ARGS[@]}" 2>&1)
init_output=$($TF_PATH -backend=false "${TF_INIT_ARGS[@]}" 2>&1)
MaxymVlasov marked this conversation as resolved.
Show resolved Hide resolved
exit_code=$?

if [ $exit_code -eq 0 ]; then
Expand Down
2 changes: 1 addition & 1 deletion hooks/terraform_fmt.sh
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function per_dir_hook_unique_part {
local -a -r args=("$@")

# pass the arguments to hook
terraform fmt "${args[@]}"
$TF_PATH fmt "${args[@]}"

# return exit code to common::per_dir_hook
local exit_code=$?
Expand Down
Loading