While watching this talk from Hashiconf 2017 - Terraform Abstractions for Safety and Power by Calvin French-Owen, I learned about this lovely tool: terraform-docs, which generates documentation based on the inputs and outputs of your Terraform modules. Since I am not the biggest fan of keeping documentation in sync manually, I wanted to use terraform-docs plus a git-hook to handle this process for for me. That turned out pretty easy.

Script for Generating Docs

Here is a simple script that searches through all the folders within a project and generates a README for each. If any READMEs are only 1 byte (for the find command -c stands for bytes), it will delete that file. Finally it prints out all the READMEs in the project.


find . -type d -exec bash -c 'terraform-docs md "{}" > "{}"/README.md;' \;

find . -name "README.md" -size 1c -type f -delete

printf "\n\033[35;1mUpdating the following READMEs with terraform-docs\033[0m\n\n"
find . -name "README.md"

Note: We end up with these single byte READMEs, when we run terraform-docs in folders that have no Terraform inputs or outputs. We could be more intelligent about not running terraform-docs in these folders, but for a quick fix, simply deleting them after they are created gets the job done. If you have any alternate implementations please reach out and share them!

I then place this script at the root of the project in a folder called scripts: scripts/generate_docs.sh and now we can run this script anytime we want to update all our module READMEs. However we don't to rely on running this by hand. So....

Creating a Githook

Here is an example of a pre-commit hook, that will call the update_docs.sh script, and then add all the README files to your index. This way in every commit you will get updated READMEs as well.

In your project you would want this located at: .git/hooks/pre-commit


"$(dirname $0)/../../scripts/generate_docs.sh"

git add "./*README.md"

NOTE: if you have unstaged changes in a README that you DON'T want committed, you will not be able to use this githook. You can skip running your githooks with --no-verify and simply run the generate_docs.sh script manually.

Another option is to use a post-commit hook to add a separate commit for the README updates. This could potentially making code reviews easier.

in .git/hooks/post-commit


"$(dirname $0)/../../scripts/generate_docs.sh"

git add "./*README.md"
git commit -m "Updating Terraform Modules with terraform-docs"

For an example of this in action, I added this script to my fork of Segment's Stack Repo (which was also mentioned in the talk) and ran it. You can see an example of a README generated here. They all look something like this:

Overall this was a quick and easy way to document the high level view of how to use a module, with minimal effort (just my style!). Special thanks to Calvin French Owen for the excellent talk and Amir Abu Shareb for making this awesome tool!