feat: rename pre-commit-terraform to pre-commit-opentofu, pt III

This commit is contained in:
Alexander Sharov 2024-01-17 00:44:43 +01:00
commit 233f6c6c8b
18 changed files with 103 additions and 103 deletions

View file

@ -21,14 +21,14 @@ Enjoy the clean, valid, and documented code!
## Run and debug hooks locally ## Run and debug hooks locally
```bash ```bash
pre-commit try-repo {-a} /path/to/local/pre-commit-terraform/repo {hook_name} pre-commit try-repo {-a} /path/to/local/pre-commit-opentofu/repo {hook_name}
``` ```
I.e. I.e.
```bash ```bash
pre-commit try-repo /mnt/c/Users/tf/pre-commit-terraform terraform_fmt # Run only `terraform_fmt` check pre-commit try-repo /mnt/c/Users/tf/pre-commit-opentofu terraform_fmt # Run only `terraform_fmt` check
pre-commit try-repo -a ~/pre-commit-terraform # run all existing checks from repo pre-commit try-repo -a ~/pre-commit-opentofu # run all existing checks from repo
``` ```
Running `pre-commit` with `try-repo` ignores all arguments specified in `.pre-commit-config.yaml`. Running `pre-commit` with `try-repo` ignores all arguments specified in `.pre-commit-config.yaml`.
@ -38,7 +38,7 @@ If you need to test hook with arguments, follow [pre-commit doc](https://pre-com
For example, to test that the [`terraform_fmt`](../README.md#terraform_fmt) hook works fine with arguments: For example, to test that the [`terraform_fmt`](../README.md#terraform_fmt) hook works fine with arguments:
```bash ```bash
/tmp/pre-commit-terraform/terraform_fmt.sh --args=-diff --args=-write=false test-dir/main.tf test-dir/vars.tf /tmp/pre-commit-opentofu/terraform_fmt.sh --args=-diff --args=-write=false test-dir/main.tf test-dir/vars.tf
``` ```
## Run hook performance test ## Run hook performance test
@ -50,7 +50,7 @@ Script accept next options:
| # | Name | Example value | Description | | # | Name | Example value | Description |
| --- | ---------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------- | | --- | ---------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------- |
| 1 | `TEST_NUM` | `200` | How many times need repeat test | | 1 | `TEST_NUM` | `200` | How many times need repeat test |
| 2 | `TEST_COMMAND` | `'pre-commit try-repo -a /tmp/159/pre-commit-terraform terraform_tfsec'` | Valid pre-commit command | | 2 | `TEST_COMMAND` | `'pre-commit try-repo -a /tmp/159/pre-commit-opentofu terraform_tfsec'` | Valid pre-commit command |
| 3 | `TEST_DIR` | `'/tmp/infrastructure'` | Dir on what you run tests. | | 3 | `TEST_DIR` | `'/tmp/infrastructure'` | Dir on what you run tests. |
| 4 | `TEST_DESCRIPTION` | ```'`terraform_tfsec` PR #123:'``` | Text that you'd like to see in result | | 4 | `TEST_DESCRIPTION` | ```'`terraform_tfsec` PR #123:'``` | Text that you'd like to see in result |
| 5 | `RAW_TEST_`<br>`RESULTS_FILE_NAME` | `terraform_tfsec_pr123` | (Temporary) File where all test data will be stored. | | 5 | `RAW_TEST_`<br>`RESULTS_FILE_NAME` | `terraform_tfsec_pr123` | (Temporary) File where all test data will be stored. |
@ -66,14 +66,14 @@ Script accept next options:
# Install deps # Install deps
sudo apt install -y datamash sudo apt install -y datamash
# Run tests # Run tests
./hooks_performance_test.sh 200 'pre-commit try-repo -a /tmp/159/pre-commit-terraform terraform_tfsec' '/tmp/infrastructure' '`terraform_tfsec` v1.51.0:' 'terraform_tfsec_pr159' ./hooks_performance_test.sh 200 'pre-commit try-repo -a /tmp/159/pre-commit-opentofu terraform_tfsec' '/tmp/infrastructure' '`terraform_tfsec` v1.51.0:' 'terraform_tfsec_pr159'
``` ```
### Run via Docker ### Run via Docker
```bash ```bash
# Build `pre-commit-terraform` image # Build `pre-commit-opentofu` image
docker build -t pre-commit-terraform --build-arg INSTALL_ALL=true . docker build -t pre-commit-opentofu --build-arg INSTALL_ALL=true .
# Build test image # Build test image
docker build -t pre-commit-tests tests/ docker build -t pre-commit-tests tests/
# Run # Run

View file

@ -7,7 +7,7 @@ labels:
--- ---
<!-- <!--
Thank you for helping to improve pre-commit-terraform! Thank you for helping to improve pre-commit-opentofu!
Please be sure to search for open issues before raising a new one. We use issues Please be sure to search for open issues before raising a new one. We use issues
for bug reports and feature requests. Please note, this template is for bugs for bug reports and feature requests. Please note, this template is for bugs

View file

@ -7,7 +7,7 @@ labels:
--- ---
<!-- <!--
Thank you for helping to improve pre-commit-terraform! Thank you for helping to improve pre-commit-opentofu!
Please be sure to search for open issues before raising a new one. We use issues Please be sure to search for open issues before raising a new one. We use issues
for bug reports and feature requests. Please note, this template is for bugs for bug reports and feature requests. Please note, this template is for bugs

View file

@ -6,7 +6,7 @@ labels:
--- ---
<!-- <!--
Thank you for helping to improve pre-commit-terraform! Thank you for helping to improve pre-commit-opentofu!
Please be sure to search for open issues before raising a new one. We use issues Please be sure to search for open issues before raising a new one. We use issues
for bug reports and feature requests. Please note, this template is for feature for bug reports and feature requests. Please note, this template is for feature
@ -22,8 +22,8 @@ implement it sensibly.
---> --->
### How could pre-commit-terraform help solve your problem? ### How could pre-commit-opentofu help solve your problem?
<!-- <!--
Let us know how you think pre-commit-terraform could help with your use case. Let us know how you think pre-commit-opentofu could help with your use case.
--> -->

View file

@ -1,5 +1,5 @@
<!-- <!--
Thank you for helping to improve pre-commit-terraform! Thank you for helping to improve pre-commit-opentofu!
--> -->
Put an `x` into the box if that apply: Put an `x` into the box if that apply:
@ -15,7 +15,7 @@ Put an `x` into the box if that apply:
Briefly describe what this pull request does. Be sure to direct your reviewers' Briefly describe what this pull request does. Be sure to direct your reviewers'
attention to anything that needs special consideration. attention to anything that needs special consideration.
We love pull requests that resolve an open pre-commit-terraform issue. If yours does, you We love pull requests that resolve an open pre-commit-opentofu issue. If yours does, you
can uncomment the below line to indicate which issue your PR fixes, for example can uncomment the below line to indicate which issue your PR fixes, for example
"Fixes #123456": "Fixes #123456":
--> -->

View file

@ -1,16 +1,16 @@
- id: infracost_breakdown - id: infracost_breakdown
name: Infracost breakdown name: Infracost breakdown
description: Check terraform infrastructure cost description: Check OpenTofu infrastructure cost
entry: hooks/infracost_breakdown.sh entry: hooks/infracost_breakdown.sh
language: script language: script
require_serial: true require_serial: true
files: \.(tf(vars)?|hcl)$ files: \.(tf(vars)?|hcl)$
exclude: \.terraform\/.*$ exclude: \.terraform\/.*$
- id: terraform_fmt - id: tofu_fmt
name: Terraform fmt name: OpenTofu fmt
description: Rewrites all Terraform configuration files to a canonical format. description: Rewrites all OpenTofu configuration files to a canonical format.
entry: hooks/terraform_fmt.sh entry: hooks/tofu_fmt.sh
language: script language: script
files: (\.tf|\.tfvars)$ files: (\.tf|\.tfvars)$
exclude: \.terraform\/.*$ exclude: \.terraform\/.*$
@ -42,27 +42,27 @@
files: (\.tf)$ files: (\.tf)$
exclude: \.terraform\/.*$ exclude: \.terraform\/.*$
- id: terraform_validate - id: tofu_validate
name: Terraform validate name: OpenTofu validate
description: Validates all Terraform configuration files. description: Validates all OpenTofu configuration files.
require_serial: true require_serial: true
entry: hooks/terraform_validate.sh entry: hooks/tofu_validate.sh
language: script language: script
files: (\.tf|\.tfvars)$ files: (\.tf|\.tfvars)$
exclude: \.terraform\/.*$ exclude: \.terraform\/.*$
- id: terraform_providers_lock - id: terraform_providers_lock
name: Lock terraform provider versions name: Lock OpenTofu provider versions
description: Updates provider signatures in dependency lock files. description: Updates provider signatures in dependency lock files.
require_serial: true require_serial: true
entry: hooks/terraform_providers_lock.sh entry: hooks/tofu_providers_lock.sh
language: script language: script
files: (\.terraform\.lock\.hcl)$ files: (\.terraform\.lock\.hcl)$
exclude: \.terraform\/.*$ exclude: \.terraform\/.*$
- id: terraform_tflint - id: terraform_tflint
name: Terraform validate with tflint name: OpenTofu validate with tflint
description: Validates all Terraform configuration files with TFLint. description: Validates all OpenTofu configuration files with TFLint.
require_serial: true require_serial: true
entry: hooks/terraform_tflint.sh entry: hooks/terraform_tflint.sh
language: script language: script
@ -86,16 +86,16 @@
exclude: \.terraform\/.*$ exclude: \.terraform\/.*$
- id: terraform_tfsec - id: terraform_tfsec
name: Terraform validate with tfsec (deprecated, use "terraform_trivy") name: OpenTofu validate with tfsec (deprecated, use "terraform_trivy")
description: Static analysis of Terraform templates to spot potential security issues. description: Static analysis of OpenTofu templates to spot potential security issues.
require_serial: true require_serial: true
entry: hooks/terraform_tfsec.sh entry: hooks/terraform_tfsec.sh
files: \.tf(vars)?$ files: \.tf(vars)?$
language: script language: script
- id: terraform_trivy - id: terraform_trivy
name: Terraform validate with trivy name: OpenTofu validate with trivy
description: Static analysis of Terraform templates to spot potential security issues. description: Static analysis of OpenTofu templates to spot potential security issues.
require_serial: true require_serial: true
entry: hooks/terraform_trivy.sh entry: hooks/terraform_trivy.sh
files: \.tf(vars)?$ files: \.tf(vars)?$
@ -103,7 +103,7 @@
- id: checkov - id: checkov
name: checkov (deprecated, use "terraform_checkov") name: checkov (deprecated, use "terraform_checkov")
description: Runs checkov on Terraform templates. description: Runs checkov on OpenTofu templates.
entry: checkov -d . entry: checkov -d .
language: python language: python
pass_filenames: false pass_filenames: false
@ -112,10 +112,10 @@
exclude: \.terraform\/.*$ exclude: \.terraform\/.*$
require_serial: true require_serial: true
- id: terraform_checkov - id: tofu_checkov
name: Checkov name: Checkov
description: Runs checkov on Terraform templates. description: Runs checkov on OpenTofu templates.
entry: hooks/terraform_checkov.sh entry: hooks/tofu_checkov.sh
language: script language: script
always_run: false always_run: false
files: \.tf$ files: \.tf$
@ -124,7 +124,7 @@
- id: terraform_wrapper_module_for_each - id: terraform_wrapper_module_for_each
name: Terraform wrapper with for_each in module name: Terraform wrapper with for_each in module
description: Generate Terraform wrappers with for_each in module. description: Generate OpenTofu wrappers with for_each in module.
entry: hooks/terraform_wrapper_module_for_each.sh entry: hooks/terraform_wrapper_module_for_each.sh
language: script language: script
pass_filenames: false pass_filenames: false
@ -135,7 +135,7 @@
- id: terrascan - id: terrascan
name: terrascan name: terrascan
description: Runs terrascan on Terraform templates. description: Runs terrascan on OpenTofu templates.
language: script language: script
entry: hooks/terrascan.sh entry: hooks/terrascan.sh
files: \.tf$ files: \.tf$
@ -144,7 +144,7 @@
- id: tfupdate - id: tfupdate
name: tfupdate name: tfupdate
description: Runs tfupdate on Terraform templates. description: Runs tfupdate on OpenTofu templates.
language: script language: script
entry: hooks/tfupdate.sh entry: hooks/tfupdate.sh
args: args:

View file

@ -5,7 +5,7 @@
Want to contribute? Check [open issues](https://github.com/tofuutils/pre-commit-opentofu/issues?q=label%3A%22good+first+issue%22+is%3Aopen+sort%3Aupdated-desc) and [contributing notes](/.github/CONTRIBUTING.md). Want to contribute? Check [open issues](https://github.com/tofuutils/pre-commit-opentofu/issues?q=label%3A%22good+first+issue%22+is%3Aopen+sort%3Aupdated-desc) and [contributing notes](/.github/CONTRIBUTING.md).
## Sponsors ## Sponsors
If you are using `pre-commit-terraform` already or want to support its development and [many other open-source projects](https://github.com/tofuutils), please become a [GitHub Sponsor](https://github.com/sponsors/tofuutils)! If you are using `pre-commit-opentofu` already or want to support its development and [many other open-source projects](https://github.com/tofuutils), please become a [GitHub Sponsor](https://github.com/sponsors/tofuutils)!
## Table of content ## Table of content
@ -92,15 +92,15 @@ When hooks-related `--build-arg`s are not specified, only the latest version of
```bash ```bash
git clone git@github.com:tofuutils/pre-commit-opentofu.git git clone git@github.com:tofuutils/pre-commit-opentofu.git
cd pre-commit-terraform cd pre-commit-opentofu
# Install the latest versions of all the tools # Install the latest versions of all the tools
docker build -t pre-commit-terraform --build-arg INSTALL_ALL=true . docker build -t pre-commit-opentofu --build-arg INSTALL_ALL=true .
``` ```
To install a specific version of individual tools, define it using `--build-arg` arguments or set it to `latest`: To install a specific version of individual tools, define it using `--build-arg` arguments or set it to `latest`:
```bash ```bash
docker build -t pre-commit-terraform \ docker build -t pre-commit-opentofu \
--build-arg PRE_COMMIT_VERSION=latest \ --build-arg PRE_COMMIT_VERSION=latest \
--build-arg TERRAFORM_VERSION=latest \ --build-arg TERRAFORM_VERSION=latest \
--build-arg CHECKOV_VERSION=2.0.405 \ --build-arg CHECKOV_VERSION=2.0.405 \
@ -456,9 +456,9 @@ Unlike most other hooks, this hook triggers once if there are any changed files
1. `terraform_docs` and `terraform_docs_without_aggregate_type_defaults` will insert/update documentation generated by [terraform-docs](https://github.com/terraform-docs/terraform-docs) framed by markers: 1. `terraform_docs` and `terraform_docs_without_aggregate_type_defaults` will insert/update documentation generated by [terraform-docs](https://github.com/terraform-docs/terraform-docs) framed by markers:
```txt ```txt
<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK --> <!-- BEGINNING OF PRE-COMMIT-OPENTOFU DOCS HOOK -->
<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK --> <!-- END OF PRE-COMMIT-OPENTOFU DOCS HOOK -->
``` ```
if they are present in `README.md`. if they are present in `README.md`.
@ -473,8 +473,8 @@ Unlike most other hooks, this hook triggers once if there are any changed files
To migrate to `terraform-docs` insertion markers, run in repo root: To migrate to `terraform-docs` insertion markers, run in repo root:
```bash ```bash
grep -rl 'BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK' . | xargs sed -i 's/BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK/BEGIN_TF_DOCS/g' grep -rl 'BEGINNING OF PRE-COMMIT-OPENTOFU DOCS HOOK' . | xargs sed -i 's/BEGINNING OF PRE-COMMIT-OPENTOFU DOCS HOOK/BEGIN_TF_DOCS/g'
grep -rl 'END OF PRE-COMMIT-TERRAFORM DOCS HOOK' . | xargs sed -i 's/END OF PRE-COMMIT-TERRAFORM DOCS HOOK/END_TF_DOCS/g' grep -rl 'END OF PRE-COMMIT-OPENTOFU DOCS HOOK' . | xargs sed -i 's/END OF PRE-COMMIT-OPENTOFU DOCS HOOK/END_TF_DOCS/g'
``` ```
```yaml ```yaml
@ -669,7 +669,7 @@ To replicate functionality in `terraform_docs` hook:
- --args=--config=__GIT_WORKING_DIR__/.tflint.hcl - --args=--config=__GIT_WORKING_DIR__/.tflint.hcl
``` ```
3. By default, pre-commit-terraform performs directory switching into the terraform modules for you. If you want to delgate the directory changing to the binary - this will allow tflint to determine the full paths for error/warning messages, rather than just module relative paths. *Note: this requires `tflint>=0.44.0`.* For example: 3. By default, pre-commit-opentofu performs directory switching into the terraform modules for you. If you want to delgate the directory changing to the binary - this will allow tflint to determine the full paths for error/warning messages, rather than just module relative paths. *Note: this requires `tflint>=0.44.0`.* For example:
```yaml ```yaml
- id: terraform_tflint - id: terraform_tflint
@ -1018,7 +1018,7 @@ machine github.com
Finally, you can execute `docker run` with an additional volume mount so that the `~/.netrc` is accessible within the container Finally, you can execute `docker run` with an additional volume mount so that the `~/.netrc` is accessible within the container
```bash ```bash
# run pre-commit-terraform with docker # run pre-commit-opentofu with docker
# adding volume for .netrc file # adding volume for .netrc file
# .netrc needs to be in /root/ dir # .netrc needs to be in /root/ dir
docker run --rm -e "USERID=$(id -u):$(id -g)" -v ~/.netrc:/root/.netrc -v $(pwd):/lint -w /lint ghcr.io/tofuutils/pre-commit-opentofu:latest run -a docker run --rm -e "USERID=$(id -u):$(id -g)" -v ~/.netrc:/root/.netrc -v $(pwd):/lint -w /lint ghcr.io/tofuutils/pre-commit-opentofu:latest run -a

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

View file

@ -37,7 +37,7 @@ function common::parse_cmdline {
# common global arrays. # common global arrays.
# Populated via `common::parse_cmdline` and can be used inside hooks' functions # Populated via `common::parse_cmdline` and can be used inside hooks' functions
ARGS=() HOOK_CONFIG=() FILES=() ARGS=() HOOK_CONFIG=() FILES=()
# Used inside `common::terraform_init` function # Used inside `common::tofu_init` function
TF_INIT_ARGS=() TF_INIT_ARGS=()
# Used inside `common::export_provided_env_vars` function # Used inside `common::export_provided_env_vars` function
ENV_VARS=() ENV_VARS=()
@ -302,38 +302,38 @@ function common::colorify {
} }
####################################################################### #######################################################################
# Run terraform init command # Run tofu init command
# Arguments: # Arguments:
# command_name (string) command that will tun after successful init # command_name (string) command that will tun after successful init
# dir_path (string) PATH to dir relative to git repo root. # dir_path (string) PATH to dir relative to git repo root.
# Can be used in error logging # Can be used in error logging
# Globals (init and populate): # Globals (init and populate):
# TF_INIT_ARGS (array) arguments for `terraform init` command # TF_INIT_ARGS (array) arguments for `tofu init` command
# Outputs: # Outputs:
# If failed - print out terraform init output # If failed - print out tofu init output
####################################################################### #######################################################################
# TODO: v2.0: Move it inside terraform_validate.sh # TODO: v2.0: Move it inside terraform_validate.sh
function common::terraform_init { function common::tofu_init {
local -r command_name=$1 local -r command_name=$1
local -r dir_path=$2 local -r dir_path=$2
local exit_code=0 local exit_code=0
local init_output local init_output
# Suppress terraform init color # Suppress tofu init color
if [ "$PRE_COMMIT_COLOR" = "never" ]; then if [ "$PRE_COMMIT_COLOR" = "never" ]; then
TF_INIT_ARGS+=("-no-color") TF_INIT_ARGS+=("-no-color")
fi fi
if [ ! -d .terraform/modules ] || [ ! -d .terraform/providers ]; then if [ ! -d .terraform/modules ] || [ ! -d .terraform/providers ]; then
init_output=$(terraform init -backend=false "${TF_INIT_ARGS[@]}" 2>&1) init_output=$(tofu init -backend=false "${TF_INIT_ARGS[@]}" 2>&1)
exit_code=$? exit_code=$?
if [ $exit_code -ne 0 ]; then if [ $exit_code -ne 0 ]; then
common::colorify "red" "'terraform init' failed, '$command_name' skipped: $dir_path" common::colorify "red" "'tofu init' failed, '$command_name' skipped: $dir_path"
echo -e "$init_output\n\n" echo -e "$init_output\n\n"
else else
common::colorify "green" "Command 'terraform init' successfully done: $dir_path" common::colorify "green" "Command 'tofu init' successfully done: $dir_path"
fi fi
fi fi

View file

@ -9,8 +9,8 @@ readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
# set up default insertion markers. These will be changed to the markers used by # set up default insertion markers. These will be changed to the markers used by
# terraform-docs if the hook config contains `--use-standard-markers=true` # terraform-docs if the hook config contains `--use-standard-markers=true`
insertion_marker_begin="<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->" insertion_marker_begin="<!-- BEGINNING OF PRE-COMMIT-OPENTOFU DOCS HOOK -->"
insertion_marker_end="<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->" insertion_marker_end="<!-- END OF PRE-COMMIT-OPENTOFU DOCS HOOK -->"
# these are the standard insertion markers used by terraform-docs # these are the standard insertion markers used by terraform-docs
readonly standard_insertion_marker_begin="<!-- BEGIN_TF_DOCS -->" readonly standard_insertion_marker_begin="<!-- BEGIN_TF_DOCS -->"

View file

@ -13,7 +13,7 @@ function main {
common::export_provided_env_vars "${ENV_VARS[@]}" common::export_provided_env_vars "${ENV_VARS[@]}"
common::parse_and_export_env_vars common::parse_and_export_env_vars
# Suppress terraform fmt color # Suppress tofu fmt color
if [ "$PRE_COMMIT_COLOR" = "never" ]; then if [ "$PRE_COMMIT_COLOR" = "never" ]; then
ARGS+=("-no-color") ARGS+=("-no-color")
fi fi
@ -44,7 +44,7 @@ function per_dir_hook_unique_part {
local -a -r args=("$@") local -a -r args=("$@")
# pass the arguments to hook # pass the arguments to hook
terraform fmt "${args[@]}" tofu fmt "${args[@]}"
# return exit code to common::per_dir_hook # return exit code to common::per_dir_hook
local exit_code=$? local exit_code=$?

View file

@ -13,7 +13,7 @@ function main {
common::parse_cmdline "$@" common::parse_cmdline "$@"
common::export_provided_env_vars "${ENV_VARS[@]}" common::export_provided_env_vars "${ENV_VARS[@]}"
common::parse_and_export_env_vars common::parse_and_export_env_vars
# JFYI: suppress color for `terraform providers lock` is N/A` # JFYI: suppress color for `tofu providers lock` is N/A`
# shellcheck disable=SC2153 # False positive # shellcheck disable=SC2153 # False positive
common::per_dir_hook "$HOOK_ID" "${#ARGS[@]}" "${ARGS[@]}" "${FILES[@]}" common::per_dir_hook "$HOOK_ID" "${#ARGS[@]}" "${ARGS[@]}" "${FILES[@]}"
@ -136,7 +136,7 @@ function per_dir_hook_unique_part {
common::colorify "yellow" "DEPRECATION NOTICE: We introduced '--mode' flag for this hook. common::colorify "yellow" "DEPRECATION NOTICE: We introduced '--mode' flag for this hook.
Check migration instructions at https://github.com/tofuutils/pre-commit-opentofu#terraform_providers_lock Check migration instructions at https://github.com/tofuutils/pre-commit-opentofu#terraform_providers_lock
" "
common::terraform_init 'terraform providers lock' "$dir_path" || { common::tofu_init 'OpenTofu providers lock' "$dir_path" || {
exit_code=$? exit_code=$?
return $exit_code return $exit_code
} }
@ -149,9 +149,9 @@ Check migration instructions at https://github.com/tofuutils/pre-commit-opentofu
fi fi
#? Don't require `tf init` for providers, but required `tf init` for modules #? Don't require `tf init` for providers, but required `tf init` for modules
#? Mitigated by `function match_validate_errors` from terraform_validate hook #? Mitigated by `function match_validate_errors` from tofu_validate hook
# pass the arguments to hook # pass the arguments to hook
terraform providers lock "${args[@]}" tofu providers lock "${args[@]}"
# return exit code to common::per_dir_hook # return exit code to common::per_dir_hook
exit_code=$? exit_code=$?

View file

@ -7,7 +7,7 @@ readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
# shellcheck source=_common.sh # shellcheck source=_common.sh
. "$SCRIPT_DIR/_common.sh" . "$SCRIPT_DIR/_common.sh"
# `terraform validate` requires this env variable to be set # `tofu validate` requires this env variable to be set
export AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-us-east-1} export AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-us-east-1}
function main { function main {
@ -16,7 +16,7 @@ function main {
common::export_provided_env_vars "${ENV_VARS[@]}" common::export_provided_env_vars "${ENV_VARS[@]}"
common::parse_and_export_env_vars common::parse_and_export_env_vars
# Suppress terraform validate color # Suppress tofu validate color
if [ "$PRE_COMMIT_COLOR" = "never" ]; then if [ "$PRE_COMMIT_COLOR" = "never" ]; then
ARGS+=("-no-color") ARGS+=("-no-color")
fi fi
@ -25,9 +25,9 @@ function main {
} }
####################################################################### #######################################################################
# Run `terraform validate` and match errors. Requires `jq` # Run `tofu validate` and match errors. Requires `jq`
# Arguments: # Arguments:
# validate_output (string with json) output of `terraform validate` command # validate_output (string with json) output of `tofu validate` command
# Outputs: # Outputs:
# Returns integer: # Returns integer:
# - 0 (no errors) # - 0 (no errors)
@ -66,8 +66,8 @@ function match_validate_errors {
####################################################################### #######################################################################
# Unique part of `common::per_dir_hook`. The function is executed in loop # Unique part of `common::per_dir_hook`. The function is executed in loop
# on each provided dir path. Run wrapped tool with specified arguments # on each provided dir path. Run wrapped tool with specified arguments
# 1. Check if `.terraform` dir exists and if not - run `terraform init` # 1. Check if `.terraform` dir exists and if not - run `tofu init`
# 2. Run `terraform validate` # 2. Run `tofu validate`
# 3. If at least 1 check failed - change the exit code to non-zero # 3. If at least 1 check failed - change the exit code to non-zero
# Arguments: # Arguments:
# dir_path (string) PATH to dir relative to git repo root. # dir_path (string) PATH to dir relative to git repo root.
@ -111,28 +111,28 @@ function per_dir_hook_unique_part {
esac esac
done done
# First try `terraform validate` with the hope that all deps are # First try `terratofuform validate` with the hope that all deps are
# pre-installed. That is needed for cases when `.terraform/modules` # pre-installed. That is needed for cases when `.terraform/modules`
# or `.terraform/providers` missed AND that is expected. # or `.terraform/providers` missed AND that is expected.
terraform validate "${args[@]}" &> /dev/null && { tofu validate "${args[@]}" &> /dev/null && {
exit_code=$? exit_code=$?
return $exit_code return $exit_code
} }
# In case `terraform validate` failed to execute # In case `tofu validate` failed to execute
# - check is simple `terraform init` will help # - check is simple `tofu init` will help
common::terraform_init 'terraform validate' "$dir_path" || { common::tofu_init 'tofu validate' "$dir_path" || {
exit_code=$? exit_code=$?
return $exit_code return $exit_code
} }
if [ "$retry_once_with_cleanup" != "true" ]; then if [ "$retry_once_with_cleanup" != "true" ]; then
# terraform validate only # tofu validate only
validate_output=$(terraform validate "${args[@]}" 2>&1) validate_output=$(tofu validate "${args[@]}" 2>&1)
exit_code=$? exit_code=$?
else else
# terraform validate, plus capture possible errors # tofu validate, plus capture possible errors
validate_output=$(terraform validate -json "${args[@]}" 2>&1) validate_output=$(tofu validate -json "${args[@]}" 2>&1)
exit_code=$? exit_code=$?
# Match specific validation errors # Match specific validation errors
@ -150,12 +150,12 @@ function per_dir_hook_unique_part {
common::colorify "yellow" "Re-validating: $dir_path" common::colorify "yellow" "Re-validating: $dir_path"
common::terraform_init 'terraform validate' "$dir_path" || { common::tofu_init 'tofu validate' "$dir_path" || {
exit_code=$? exit_code=$?
return $exit_code return $exit_code
} }
validate_output=$(terraform validate "${args[@]}" 2>&1) validate_output=$(tofu validate "${args[@]}" 2>&1)
exit_code=$? exit_code=$?
fi fi
fi fi

View file

@ -17,7 +17,7 @@ function main {
check_dependencies check_dependencies
# shellcheck disable=SC2153 # False positive # shellcheck disable=SC2153 # False positive
terraform_module_wrapper_ "${ARGS[*]}" tofu_module_wrapper_ "${ARGS[*]}"
} }
readonly CONTENT_MAIN_TF='module "wrapper" {}' readonly CONTENT_MAIN_TF='module "wrapper" {}'
@ -38,12 +38,12 @@ readonly CONTENT_OUTPUTS_TF='output "wrapper" {
WRAPPER_OUTPUT_SENSITIVE WRAPPER_OUTPUT_SENSITIVE
}' }'
readonly CONTENT_VERSIONS_TF='terraform { readonly CONTENT_VERSIONS_TF='terraform {
required_version = ">= 0.13.1" required_version = ">= 1.6.0"
}' }'
# shellcheck disable=SC2016 # False positive # shellcheck disable=SC2016 # False positive
readonly CONTENT_README='# WRAPPER_TITLE readonly CONTENT_README='# WRAPPER_TITLE
The configuration in this directory contains an implementation of a single module wrapper pattern, which allows managing several copies of a module in places where using the native Terraform 0.13+ `for_each` feature is not feasible (e.g., with Terragrunt). The configuration in this directory contains an implementation of a single module wrapper pattern, which allows managing several copies of a module in places where using the native OpenTofu 1.6.0+ `for_each` feature is not feasible (e.g., with Terragrunt).
You may want to use a single Terragrunt configuration file to manage multiple resources without duplicating `terragrunt.hcl` files for each copy of the same module. You may want to use a single Terragrunt configuration file to manage multiple resources without duplicating `terragrunt.hcl` files for each copy of the same module.
@ -64,7 +64,7 @@ inputs = {
defaults = { # Default values defaults = { # Default values
create = true create = true
tags = { tags = {
Terraform = "true" OpenTofu = "true"
Environment = "dev" Environment = "dev"
} }
} }
@ -81,7 +81,7 @@ inputs = {
} }
``` ```
## Usage with Terraform ## Usage with OpenTofu
```hcl ```hcl
module "wrapper" { module "wrapper" {
@ -90,7 +90,7 @@ module "wrapper" {
defaults = { # Default values defaults = { # Default values
create = true create = true
tags = { tags = {
Terraform = "true" OpenTofu = "true"
Environment = "dev" Environment = "dev"
} }
} }
@ -142,7 +142,7 @@ inputs = {
} }
```' ```'
function terraform_module_wrapper_ { function tofu_module_wrapper_ {
local args local args
read -r -a args <<< "$1" read -r -a args <<< "$1"
@ -197,7 +197,7 @@ function terraform_module_wrapper_ {
cat << EOF cat << EOF
ERROR: Unrecognized argument: $key ERROR: Unrecognized argument: $key
Hook ID: $HOOK_ID. Hook ID: $HOOK_ID.
Generate Terraform module wrapper. Available arguments: Generate OpenTofu module wrapper. Available arguments:
--root-dir=... - Root dir of the repository (Optional) --root-dir=... - Root dir of the repository (Optional)
--module-dir=... - Single module directory. Options: "." (means just root module), --module-dir=... - Single module directory. Options: "." (means just root module),
"modules/iam-user" (a single module), or empty (means include all "modules/iam-user" (a single module), or empty (means include all
@ -212,7 +212,7 @@ Generate Terraform module wrapper. Available arguments:
Example: Example:
--module-dir=modules/object - Generate wrapper for one specific submodule. --module-dir=modules/object - Generate wrapper for one specific submodule.
--module-dir=. - Generate wrapper for the root module. --module-dir=. - Generate wrapper for the root module.
--module-repo-org=terraform-google-modules --module-repo-shortname=network --module-repo-provider=google - Generate wrappers for repository available by name "terraform-google-modules/network/google" in the Terraform registry and it includes all modules (root and in "modules/*"). --module-repo-org=terraform-google-modules --module-repo-shortname=network --module-repo-provider=google - Generate wrappers for repository available by name "terraform-google-modules/network/google" in the OpenTofu registry and it includes all modules (root and in "modules/*").
EOF EOF
exit 1 exit 1
;; ;;
@ -310,7 +310,7 @@ EOF
echo echo
fi fi
# Read content of all terraform files # Read content of all OpenTofu files
# shellcheck disable=SC2207 # shellcheck disable=SC2207
all_tf_content=$(find "${full_module_dir}" -name '*.tf' -maxdepth 1 -type f -exec cat {} +) all_tf_content=$(find "${full_module_dir}" -name '*.tf' -maxdepth 1 -type f -exec cat {} +)
@ -319,15 +319,15 @@ EOF
continue continue
fi fi
# Get names of module variables in all terraform files # Get names of module variables in all OpenTofu files
# shellcheck disable=SC2207 # shellcheck disable=SC2207
module_vars=($(echo "$all_tf_content" | hcledit block list | { grep "^variable\." | cut -d'.' -f 2 | sort || true; })) module_vars=($(echo "$all_tf_content" | hcledit block list | { grep "^variable\." | cut -d'.' -f 2 | sort || true; }))
# Get names of module outputs in all terraform files # Get names of module outputs in all OpenTofu files
# shellcheck disable=SC2207 # shellcheck disable=SC2207
module_outputs=($(echo "$all_tf_content" | hcledit block list | { grep "^output\." | cut -d'.' -f 2 || true; })) module_outputs=($(echo "$all_tf_content" | hcledit block list | { grep "^output\." | cut -d'.' -f 2 || true; }))
# Get names of module providers in all terraform files # Get names of module providers in all OpenTofu files
module_providers=$(echo "$all_tf_content" | hcledit block list | { grep "^provider\." || true; }) module_providers=$(echo "$all_tf_content" | hcledit block list | { grep "^provider\." || true; })
if [[ $module_providers ]]; then if [[ $module_providers ]]; then
@ -342,7 +342,7 @@ EOF
# At least one output is sensitive - the wrapper's output should be sensitive, too # At least one output is sensitive - the wrapper's output should be sensitive, too
if [[ "$module_output_sensitive" == "true" ]]; then if [[ "$module_output_sensitive" == "true" ]]; then
wrapper_output_sensitive="sensitive = true # At least one sensitive module output (${module_output}) found (requires Terraform 0.14+)" wrapper_output_sensitive="sensitive = true # At least one sensitive module output (${module_output}) found (requires OpenTofu 1.6.0+)"
break break
fi fi
done done

View file

@ -40,7 +40,7 @@ function per_dir_hook_unique_part {
local -a -r args=("$@") local -a -r args=("$@")
# pass the arguments to hook # pass the arguments to hook
terrascan scan -i terraform "${args[@]}" terrascan scan -i tofu "${args[@]}"
# return exit code to common::per_dir_hook # return exit code to common::per_dir_hook
local exit_code=$? local exit_code=$?
@ -57,7 +57,7 @@ function run_hook_on_whole_repo {
local -a -r args=("$@") local -a -r args=("$@")
# pass the arguments to hook # pass the arguments to hook
terrascan scan -i terraform "${args[@]}" terrascan scan -i tofu "${args[@]}"
# return exit code to common::per_dir_hook # return exit code to common::per_dir_hook
local exit_code=$? local exit_code=$?

View file

@ -1,4 +1,4 @@
FROM pre-commit-terraform:latest FROM pre-commit-opentofu:latest
RUN apt update && \ RUN apt update && \
apt install -y \ apt install -y \

View file

@ -1,10 +1,10 @@
#!/usr/bin/env bash #!/usr/bin/env bash
TEST_NUM=$1 # 1000 TEST_NUM=$1 # 1000
TEST_COMMAND=$2 # 'pre-commit try-repo -a /tmp/159/pre-commit-terraform terraform_tfsec' TEST_COMMAND=$2 # 'pre-commit try-repo -a /tmp/159/pre-commit-opentofu tofu_tfsec'
TEST_DIR=$3 # '/tmp/infrastructure' TEST_DIR=$3 # '/tmp/infrastructure'
TEST_DESCRIPTION="$TEST_NUM runs '$4'" # '`terraform_tfsec` PR #123:' TEST_DESCRIPTION="$TEST_NUM runs '$4'" # '`tofu_tfsec` PR #123:'
RAW_TEST_RESULTS_FILE_NAME=$5 # terraform_tfsec_pr123 RAW_TEST_RESULTS_FILE_NAME=$5 # tofu_tfsec_pr123
function run_tests { function run_tests {
local TEST_NUM=$1 local TEST_NUM=$1