Skip to content

Commit 96fe3ef

Browse files
authored
feat: Add --retry-once-with-cleanup to terraform_validate (antonbabenko#441)
1 parent a15204b commit 96fe3ef

File tree

3 files changed

+140
-22
lines changed

3 files changed

+140
-22
lines changed

README.md

Lines changed: 44 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ If you are using `pre-commit-terraform` already or want to support its developme
8080
* [`TFLint`](https://github.com/terraform-linters/tflint) required for `terraform_tflint` hook.
8181
* [`TFSec`](https://github.com/liamg/tfsec) required for `terraform_tfsec` hook.
8282
* [`infracost`](https://github.com/infracost/infracost) required for `infracost_breakdown` hook.
83-
* [`jq`](https://github.com/stedolan/jq) required for `infracost_breakdown` hook.
83+
* [`jq`](https://github.com/stedolan/jq) required for `terraform_validate` with `--retry-once-with-cleanup` flag, and for `infracost_breakdown` hook.
8484
* [`tfupdate`](https://github.com/minamijoyo/tfupdate) required for `tfupdate` hook.
8585
* [`hcledit`](https://github.com/minamijoyo/hcledit) required for `terraform_wrapper_module_for_each` hook.
8686

@@ -238,7 +238,7 @@ pre-commit run -a
238238

239239
Or, using Docker ([available tags](https://github.com/antonbabenko/pre-commit-terraform/pkgs/container/pre-commit-terraform/versions)):
240240

241-
**NOTE:** This command uses your user id and group id for the docker container to use to access the local files. If the files are owned by another user, update the `USERID` environment variable. See [File Permissions section](#docker-usage-file-permissions) for more information.
241+
> Note: This command uses your user id and group id for the docker container to use to access the local files. If the files are owned by another user, update the `USERID` environment variable. See [File Permissions section](#docker-usage-file-permissions) for more information.
242242
243243
```bash
244244
TAG=latest
@@ -258,7 +258,7 @@ There are several [pre-commit](https://pre-commit.com/) hooks to keep Terraform
258258

259259
<!-- markdownlint-disable no-inline-html -->
260260
| Hook name | Description | Dependencies<br><sup>[Install instructions here](#1-install-dependencies)</sup> |
261-
| ------------------------------------------------------ |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
261+
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
262262
| `checkov` and `terraform_checkov` | [checkov](https://github.com/bridgecrewio/checkov) static analysis of terraform templates to spot potential security issues. [Hook notes](#checkov-deprecated-and-terraform_checkov) | `checkov`<br>Ubuntu deps: `python3`, `python3-pip` |
263263
| `infracost_breakdown` | Check how much your infra costs with [infracost](https://github.com/infracost/infracost). [Hook notes](#infracost_breakdown) | `infracost`, `jq`, [Infracost API key](https://www.infracost.io/docs/#2-get-api-key) |
264264
| `terraform_docs` | Inserts input and output documentation into `README.md`. Recommended. [Hook notes](#terraform_docs) | `terraform-docs` |
@@ -268,11 +268,11 @@ There are several [pre-commit](https://pre-commit.com/) hooks to keep Terraform
268268
| `terraform_providers_lock` | Updates provider signatures in [dependency lock files](https://www.terraform.io/docs/cli/commands/providers/lock.html). [Hook notes](#terraform_providers_lock) | - |
269269
| `terraform_tflint` | Validates all Terraform configuration files with [TFLint](https://github.com/terraform-linters/tflint). [Available TFLint rules](https://github.com/terraform-linters/tflint/tree/master/docs/rules#rules). [Hook notes](#terraform_tflint). | `tflint` |
270270
| `terraform_tfsec` | [TFSec](https://github.com/aquasecurity/tfsec) static analysis of terraform templates to spot potential security issues. [Hook notes](#terraform_tfsec) | `tfsec` |
271-
| `terraform_validate` | Validates all Terraform configuration files. [Hook notes](#terraform_validate) | - |
271+
| `terraform_validate` | Validates all Terraform configuration files. [Hook notes](#terraform_validate) | `jq`, only for `--retry-once-with-cleanup` flag |
272272
| `terragrunt_fmt` | Reformat all [Terragrunt](https://github.com/gruntwork-io/terragrunt) configuration files (`*.hcl`) to a canonical format. | `terragrunt` |
273273
| `terragrunt_validate` | Validates all [Terragrunt](https://github.com/gruntwork-io/terragrunt) configuration files (`*.hcl`) | `terragrunt` |
274274
| `terraform_wrapper_module_for_each` | Generates Terraform wrappers with `for_each` in module. [Hook notes](#terraform_wrapper_module_for_each) | `hcledit` |
275-
| `terrascan` | [terrascan](https://github.com/tenable/terrascan) Detect compliance and security violations. [Hook notes](#terrascan) | `terrascan` |
275+
| `terrascan` | [terrascan](https://github.com/tenable/terrascan) Detect compliance and security violations. [Hook notes](#terrascan) | `terrascan` |
276276
| `tfupdate` | [tfupdate](https://github.com/minamijoyo/tfupdate) Update version constraints of Terraform core, providers, and modules. [Hook notes](#tfupdate) | `tfupdate` |
277277
<!-- markdownlint-enable no-inline-html -->
278278

@@ -284,8 +284,9 @@ Check the [source file](https://github.com/antonbabenko/pre-commit-terraform/blo
284284

285285
> All, except deprecated hooks: `checkov`, `terraform_docs_replace`
286286
287-
You can use environment variables for the `--args` section.
288-
Note: You _must_ use the `${ENV_VAR}` definition, `$ENV_VAR` will not expand.
287+
You can use environment variables for the `--args` section.
288+
289+
> **Warning**: You _must_ use the `${ENV_VAR}` definition, `$ENV_VAR` will not expand.
289290
290291
Config example:
291292

@@ -486,7 +487,7 @@ Unlike most other hooks, this hook triggers once if there are any changed files
486487
- --args=--config=.terraform-docs.yml
487488
```
488489

489-
Note: Avoid use `recursive.enabled: true` in config file, that can cause unexpected behavior.
490+
> **Warning**: Avoid use `recursive.enabled: true` in config file, that can cause unexpected behavior.
490491

491492
5. If you need some exotic settings, it can be done too. I.e. this one generates HCL files:
492493

@@ -540,7 +541,7 @@ To replicate functionality in `terraform_docs` hook:
540541

541542
1. The hook requires Terraform 0.14 or later.
542543
2. The hook invokes two operations that can be really slow:
543-
* `terraform init` (in case `.terraform` directory is not initialised)
544+
* `terraform init` (in case `.terraform` directory is not initialized)
544545
* `terraform providers lock`
545546

546547
Both operations require downloading data from remote Terraform registries, and not all of that downloaded data or meta-data is currently being cached by Terraform.
@@ -675,7 +676,31 @@ To replicate functionality in `terraform_docs` hook:
675676
- --tf-init-args=-lockfile=readonly
676677
```
677678

678-
3. It may happen that Terraform working directory (`.terraform`) already exists but not in the best condition (eg, not initialized modules, wrong version of Terraform, etc.). To solve this problem, you can find and delete all `.terraform` directories in your repository:
679+
3. It may happen that Terraform working directory (`.terraform`) already exists but not in the best condition (eg, not initialized modules, wrong version of Terraform, etc.). To solve this problem, you can delete broken `.terraform` directories in your repository:
680+
681+
**Option 1**
682+
683+
```yaml
684+
- id: terraform_validate
685+
args:
686+
- --hook-config=--retry-once-with-cleanup=true # Boolean. true or false
687+
```
688+
689+
> Note: The flag requires additional dependency to be installed: `jq`.
690+
691+
If `--retry-once-with-cleanup=true`, then 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:
692+
693+
* "Missing or corrupted provider plugins"
694+
* "Module source has changed"
695+
* "Module version requirements have changed"
696+
* "Module not installed"
697+
* "Could not load plugin"
698+
699+
**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.
700+
701+
**Option 2**
702+
703+
An alternative solution is to find and delete all `.terraform` directories in your repository:
679704

680705
```bash
681706
echo "
@@ -689,22 +714,23 @@ To replicate functionality in `terraform_docs` hook:
689714

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

692-
**Warning:** If you use Terraform workspaces, DO NOT use this workaround ([details](https://github.com/antonbabenko/pre-commit-terraform/issues/203#issuecomment-918791847)). Wait to [`force-init`](https://github.com/antonbabenko/pre-commit-terraform/issues/224) option implementation.
717+
**Warning:** 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.
693718

694719
4. `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.
695720

696721
When running the hook against Terraform code where you have provider `configuration_aliases` defined in a `required_providers` configuration block, terraform will throw an error like:
697-
>
698-
>
722+
699723
> Error: Provider configuration not present
700-
> To work with <resource> its original provider configuration at provider["registry.terraform.io/hashicorp/aws"].<provider_alias> is required, but it has been removed. This occurs when a provider configuration is removed while
701-
> objects created by that provider still exist in the state. Re-add the provider configuration to destroy <resource>, after which you can remove the provider configuration again.
724+
> To work with `<resource>` its original provider configuration at provider `["registry.terraform.io/hashicorp/aws"].<provider_alias>` is required, but it has been removed. This occurs when a provider configuration is removed while
725+
> objects created by that provider still exist in the state. Re-add the provider configuration to destroy `<resource>`, after which you can remove the provider configuration again.
702726

703727
This is a [known issue](https://github.com/hashicorp/terraform/issues/28490) with Terraform and how providers are initialized in Terraform 0.15 and later. To work around this you can add an `exclude` parameter to the configuration of `terraform_validate` hook like this:
728+
704729
```yaml
705730
- id: terraform_validate
706731
exclude: '^[^/]+$'
707732
```
733+
708734
This will exclude the root directory from being processed by this hook. Then add a subdirectory like "examples" or "tests" and put an example implementation in place that defines the providers with the proper aliases, and this will give you validation of your module through the example. If instead you are using this with multiple modules in one repository you'll want to set the path prefix in the regular expression, such as `exclude: modules/offendingmodule/[^/]+$`.
709735

710736
Alternately, you can use [terraform-config-inspect](https://github.com/hashicorp/terraform-config-inspect) and use a variant of [this script](https://github.com/bendrucker/terraform-configuration-aliases-action/blob/main/providers.sh) to generate a providers file at runtime:
@@ -722,6 +748,7 @@ To replicate functionality in `terraform_docs` hook:
722748
```
723749

724750
Save it as `.generate-providers.sh` in the root of your repository and add a `pre-commit` hook to run it before all other hooks, like so:
751+
725752
```yaml
726753
- repos:
727754
- repo: local
@@ -738,7 +765,7 @@ To replicate functionality in `terraform_docs` hook:
738765
[...]
739766
```
740767

741-
**Note:** 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.
768+
> Note: 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.
742769

743770
### terraform_wrapper_module_for_each
744771

@@ -784,7 +811,7 @@ If the generated name is incorrect, set them by providing the `module-repo-short
784811

785812
See the `terrascan run -h` command line help for available options.
786813

787-
2. Use the `--args=--verbose` parameter to see the rule ID in the scaning output. Usuful to skip validations.
814+
2. Use the `--args=--verbose` parameter to see the rule ID in the scanning output. Useful to skip validations.
788815
3. Use `--skip-rules="ruleID1,ruleID2"` parameter to skip one or more rules globally while scanning (e.g.: `--args=--skip-rules="ruleID1,ruleID2"`).
789816
4. Use the syntax `#ts:skip=RuleID optional_comment` inside a resource to skip the rule for that resource.
790817

hooks/_common.sh

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,13 +299,15 @@ function common::terraform_init {
299299
TF_INIT_ARGS+=("-no-color")
300300
fi
301301

302-
if [ ! -d .terraform ]; then
302+
if [ ! -d .terraform/modules ] || [ ! -d .terraform/providers ]; then
303303
init_output=$(terraform init -backend=false "${TF_INIT_ARGS[@]}" 2>&1)
304304
exit_code=$?
305305

306306
if [ $exit_code -ne 0 ]; then
307307
common::colorify "red" "'terraform init' failed, '$command_name' skipped: $dir_path"
308308
echo -e "$init_output\n\n"
309+
else
310+
common::colorify "green" "Command 'terraform init' successfully done: $dir_path"
309311
fi
310312
fi
311313

0 commit comments

Comments
 (0)