Skip to content

feat: Add terraform_graph hook #589

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

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

jrdnbradford
Copy link

Put an x into the box if that apply:

  • This PR introduces breaking change.
  • This PR fixes a bug.
  • This PR adds new functionality.
  • This PR enhances existing functionality.

Description of your changes

This adds a terraform_graph hook that generates charts using terraform graph and GraphViz. My org finds something like this helpful to upkeep documentation.

Test results

200 runs 'terraform_graph v0.0.1:'

time command max min mean median
users seconds 14.71 9.51 13.6592 13.84
system seconds 1.48 0.95 1.28115 1.29
CPU % 415 149 371.545 377
Total time 8.71 3.16 4.054 3.99
Run details
  • Test Start: Mon 11 Dec 2023 04:41:22 PM UTC
  • Test End: Mon 11 Dec 2023 04:54:54 PM UTC
Variable name Value
TEST_NUM 200
TEST_COMMAND pre-commit try-repo -a /home/$user/Desktop/pre-commit-terraform terraform_graph
TEST_DIR /home/$user/$repo
TEST_DESCRIPTION 200 runs 'terraform_graph v0.0.1:'
RAW_TEST_RESULTS_FILE_NAME terraform_graph_results

Memory info (head -n 6 /proc/meminfo):

MemTotal:       32519148 kB
MemFree:         8189176 kB
MemAvailable:   27378808 kB
Buffers:          571396 kB
Cached:         14010628 kB
SwapCached:          120 kB

CPU info:

Real procs: 4
Virtual (hyper-threading) procs: 8
processor	: 7
vendor_id	: GenuineIntel
cpu family	: 6
model		: 142
model name	: Intel(R) Core(TM) i7-10610U CPU @ 1.80GHz
stepping	: 12
microcode	: 0xf8
cpu MHz		: 3400.063
cache size	: 8192 KB
physical id	: 0
siblings	: 8
core id		: 3
cpu cores	: 4
apicid		: 7
initial apicid	: 7
fpu		: yes
fpu_exception	: yes
cpuid level	: 22
wp		: yes
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities
vmx flags	: vnmi preemption_timer invvpid ept_x_only ept_ad ept_1gb flexpriority tsc_offset vtpr mtf vapic ept vpid unrestricted_guest ple shadow_vmcs pml ept_mode_based_exec
bugs		: spectre_v1 spectre_v2 spec_store_bypass swapgs taa itlb_multihit srbds mmio_stale_data retbleed eibrs_pbrsb gds
bogomips	: 4599.93
clflush size	: 64
cache_alignment	: 64
address sizes	: 39 bits physical, 48 bits virtual
power management:

How can we test changes

Testing can be performed by running against a repo with *.tf files and ensuring that the correct *.svg files are output in each directory:

- repo: https://github.com/jrdnbradford/pre-commit-terraform
  rev: add-graph-hook
  hooks:
    - id: terraform_graph
      args:
      - --args=-type=plan-destroy
      - --hook-config=--path-to-file=test-config.svg

The most important configs for the hook are -type and a hook config --path-to-file that sets the name of the output *.svg.

I cannot say that I'm a particularly good shell scripter, so if there's interest in adding this please feel free to edit.

@jrdnbradford jrdnbradford changed the title Add terraform_graph hook feat: Add terraform_graph hook Dec 11, 2023
@MaxymVlasov MaxymVlasov added the feature New feature or request label Dec 11, 2023
Copy link
Collaborator

@MaxymVlasov MaxymVlasov left a comment

Choose a reason for hiding this comment

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

Please add hook and it deps to Dockerfile

And double-check https://github.com/antonbabenko/pre-commit-terraform/blob/master/.github/CONTRIBUTING.md#add-new-hook - you could miss something else

local -a -r args=("$@")

if [[ ! $(command -v dot) ]]; then
echo "ERROR: dot is required by terraform_graph pre-commit hook but is not installed or in the system's PATH."
Copy link
Collaborator

Choose a reason for hiding this comment

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

Let's add some colors

Suggested change
echo "ERROR: dot is required by terraform_graph pre-commit hook but is not installed or in the system's PATH."
common::colorify "red" "ERROR: dot is required by terraform_graph pre-commit hook but is not installed or in the system's PATH."

@@ -926,6 +930,16 @@ If the generated name is incorrect, set them by providing the `module-repo-short
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.

### terraform_graph
`terraform_graph` utilizes Terraform's built-in [`graph` command](https://developer.hashicorp.com/terraform/cli/commands/graph) and `dot` from [GraphViz](https://www.graphviz.org/) to generate charts of your configuration.

Copy link
Collaborator

@MaxymVlasov MaxymVlasov Dec 11, 2023

Choose a reason for hiding this comment

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

Would be nice to have an example image of resulting graph here

You can populate it inside assets/ dir

@jrdnbradford
Copy link
Author

@MaxymVlasov, awesome, I'll work on this. Thanks for your help.

@MaxymVlasov
Copy link
Collaborator

@jrdnbradford howdy. Do you plan to continue working on this PR? Do you need any help from our side?

@leandroscardua
Copy link

I’m really crossing my fingers that @jrdnbradford pulls off this new feature! . I'm looking forward to using it.
and share the new feature with my team

@jrdnbradford
Copy link
Author

@jrdnbradford howdy. Do you plan to continue working on this PR? Do you need any help from our side?

I was originally out of my depth here and now I don't have the extra time to get back up to speed and finish this up. Sorry about that. If someone else wants to pick up this work that would be great.

Copy link

coderabbitai bot commented Apr 30, 2025

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added a pre-commit hook to automatically generate visual dependency graphs for Terraform configurations.
  • Documentation

    • Updated the README with instructions, dependencies, and usage examples for the new Terraform graph hook, including installation steps for required tools.

Walkthrough

A new pre-commit hook called terraform_graph has been introduced, enabling the automated generation of Terraform dependency graphs in SVG format using Terraform's graph command and Graphviz's dot tool. The .pre-commit-hooks.yaml file is updated to register the new hook, while the README.md is expanded to include documentation, installation instructions, and usage examples for the hook. The implementation is provided in a new Bash script, hooks/terraform_graph.sh, which handles argument parsing, dependency checks, graph generation, and file comparison logic.

Changes

File(s) Change Summary
.pre-commit-hooks.yaml Added a new hook definition for terraform_graph that runs hooks/terraform_graph.sh on .tf files.
README.md Updated documentation: added hook description, usage examples, and Graphviz installation instructions.
hooks/terraform_graph.sh Introduced a Bash script implementing the terraform_graph pre-commit hook logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PreCommit
    participant terraform_graph.sh
    participant Terraform
    participant GraphvizDot

    User->>PreCommit: Runs pre-commit with terraform_graph hook
    PreCommit->>terraform_graph.sh: Executes hook script
    terraform_graph.sh->>terraform_graph.sh: Parse args, check for dot
    terraform_graph.sh->>Terraform: Run terraform graph
    Terraform-->>terraform_graph.sh: Outputs dependency graph (dot format)
    terraform_graph.sh->>GraphvizDot: Pipe dot format to dot (SVG output)
    GraphvizDot-->>terraform_graph.sh: Receives SVG
    terraform_graph.sh->>terraform_graph.sh: Compare with previous SVG
    terraform_graph.sh-->>PreCommit: Exit with status (based on diff)
Loading

Suggested reviewers

  • antonbabenko
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

♻️ Duplicate comments (1)
README.md (1)

1194-1196: Include a sample output image

It would be helpful to add a sample SVG (e.g., under assets/) to visually illustrate the terraform_graph output, as previously suggested.

🧹 Nitpick comments (7)
.pre-commit-hooks.yaml (1)

180-186: Anchor patterns, quote regex, and disable filename passing

To ensure precise matching, quote and anchor the files and exclude regex, and consider setting pass_filenames: false since the hook generates a single graph per directory:

- id: terraform_graph
  name: Terraform graph
  entry: hooks/terraform_graph.sh
  language: script
  files:  '^.*\.tf$'
  exclude: '^\.terraform/.*$'
  pass_filenames: false
README.md (5)

106-106: Maintain alphabetical order in dependencies list

The new graphviz dependency is inserted at the end of the list. For readability, consider placing it alphabetically (e.g., after git and before hcledit).


180-181: Improve readability of MacOS install command

The brew install line is very long. Consider splitting out the graphviz installation or grouping dependencies on separate lines:

brew install graphviz

204-204: Consolidate Ubuntu 18.04 Graphviz installation

The sudo apt install -y graphviz command is separated from the main install block. To maintain consistency, merge it with the earlier apt install invocation.


227-227: Consolidate Ubuntu 20.04+ Graphviz installation

Similarly, include graphviz alongside other packages in the apt install block for Ubuntu 20.04+.


1197-1202: Refine the usage snippet formatting

For consistency with other hook examples, indent the args items and situate this under an explicit hooks: section. For example:

- id: terraform_graph
  args:
    - --args=-type=apply  # Default is `plan`
    - --hook-config=--path-to-file=test-config.svg  # Default is tf-graph.svg
hooks/terraform_graph.sh (1)

2-2: Consider enabling strict mode (set -euo pipefail)

Add set -u to treat unset variables as errors for improved robustness:

-set -eo pipefail
+set -euo pipefail
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 521ada5 and 3d54d6c.

📒 Files selected for processing (3)
  • .pre-commit-hooks.yaml (1 hunks)
  • README.md (7 hunks)
  • hooks/terraform_graph.sh (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
hooks/terraform_graph.sh (1)
hooks/_common.sh (5)
  • common::initialize (31-36)
  • common::parse_cmdline (52-115)
  • common::export_provided_env_vars (590-608)
  • common::parse_and_export_env_vars (123-152)
  • common::per_dir_hook (285-429)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@macos-13
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.10@windows-2025
🔇 Additional comments (1)
README.md (1)

329-329: Table entry for terraform_graph looks good

The hook name, description, and dependency (dot from GraphViz) are clearly documented. Nice addition!

Comment on lines +41 to +44
if [[ ! $(command -v dot) ]]; then
echo "ERROR: dot is required by terraform_graph pre-commit hook but is not installed or in the system's PATH."
exit 1
fi
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use a robust check for GraphViz's dot executable

The current test [[ ! $(command -v dot) ]] can misfire. Prefer:

if ! command -v dot >/dev/null 2>&1; then
  common::colorify "red" "ERROR: \`dot\` is required but not found in PATH."
  exit 1
fi

This reliably detects dot and applies consistent error styling.

Comment on lines +61 to +63
temp_file=$(mktemp)
# pass the arguments to hook
echo "${args[@]}" >> per_dir_hook_unique_part
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unintended debug output

Left-over debug lines append args to files (>> per_dir_hook_unique_part), polluting the working directory. These should be removed.

temp_file=$(mktemp)
# pass the arguments to hook
echo "${args[@]}" >> per_dir_hook_unique_part
terraform graph "${args[@]}" | dot -Tsvg > "$temp_file"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Respect the detected Terraform binary path

Rather than hardcoding terraform, invoke the binary discovered by common::get_tf_binary_path. For example:

- terraform graph "${args[@]}" | dot -Tsvg > "$temp_file"
+ "$tf_path" graph "${args[@]}" | dot -Tsvg > "$temp_file"

This ensures compatibility with custom Terraform/OpenTofu installations.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
terraform graph "${args[@]}" | dot -Tsvg > "$temp_file"
- terraform graph "${args[@]}" | dot -Tsvg > "$temp_file"
+ "$tf_path" graph "${args[@]}" | dot -Tsvg > "$temp_file"

Comment on lines +83 to +84
echo "${args[@]}" >> run_hook_on_whole_repo
terraform graph "$(pwd)" "${args[@]}" | dot -Tsvg > "$text_file"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Clean up debug echo and use custom Terraform path

In run_hook_on_whole_repo, remove the debug echo and switch to the detected binary:

- echo "${args[@]}" >> run_hook_on_whole_repo
- terraform graph "$(pwd)" "${args[@]}" | dot -Tsvg > "$text_file"
+ "$tf_path" graph "$(pwd)" "${args[@]}" | dot -Tsvg > "$text_file"

This prevents stray files and honors custom binaries.

Comment on lines +67 to +72
cmp -s "$temp_file" "$text_file"

# return exit code to common::per_dir_hook
local exit_code=$?
mv "$temp_file" "$text_file"
return $exit_code
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Only update SVG on content changes

The current logic always moves the temp file, updating the SVG even when identical. This can trigger false diffs. Instead:

- cmp -s "$temp_file" "$text_file"
- local exit_code=$?
- mv "$temp_file" "$text_file"
- return $exit_code
+ if cmp -s "$temp_file" "$text_file"; then
+   rm "$temp_file"
+   return 0
+ else
+   mv "$temp_file" "$text_file"
+   return 1
+ fi

This preserves modification timestamps when no content change has occurred.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cmp -s "$temp_file" "$text_file"
# return exit code to common::per_dir_hook
local exit_code=$?
mv "$temp_file" "$text_file"
return $exit_code
# return exit code to common::per_dir_hook
if cmp -s "$temp_file" "$text_file"; then
rm "$temp_file"
return 0
else
mv "$temp_file" "$text_file"
return 1
fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants