How to Generate Terraform Documentation Using GitHub Actions: A Beginner's Guide to CI/CD Automation


As a beginner in the world of DevOps and Infrastructure as Code (IaC), you might have heard of Terraform, a powerful tool for defining and provisioning infrastructure using code. But as your Terraform projects grow, keeping your documentation up-to-date can become a challenge. Manually updating README files with details about your modules is time-consuming and error-prone. This is where automation shines, and GitHub Actions, a CI/CD platform, can help you generate Terraform documentation effortlessly.
In this article, I’ll walk you through the process of using GitHub Actions to automate the generation of Terraform documentation with the terraform-docs tool. We’ll focus on how Continuous Integration and Continuous Deployment (CI/CD) simplifies this process, ensuring your documentation is always consistent and current. By the end, you’ll have a clear understanding of how to set up a CI/CD pipeline for Terraform documentation and why it’s a game-changer for your projects.
Why Automate Terraform Documentation?
Before we dive into the technical details, let’s understand why automating documentation matters:
Consistency: Automated documentation ensures that your Terraform module details (like inputs, outputs, and resources) are accurately reflected in your README files.
Time-Saving: Instead of manually updating documentation, automation handles it for you with every code change.
Collaboration: Clear, up-to-date documentation helps team members understand and use your Terraform modules effectively.
Version Control Integration: By tying documentation updates to your GitHub repository, you maintain a single source of truth for your infrastructure code and its documentation.
CI/CD pipelines, like those built with GitHub Actions, make this automation possible by triggering workflows based on events like code pushes or pull requests. Let’s see how this works for generating Terraform documentation.
Prerequisites
To follow along, you’ll need:
A GitHub Account: Sign up at github.com if you don’t have one.
A GitHub Repository: Create a repository to store your Terraform code. You can initialize it with a README.md and select the Terraform .gitignore template.
Basic Terraform Knowledge: Familiarity with Terraform modules, such as inputs, outputs, and resources, is helpful. If you’re new, check out HashiCorp’s Get Started tutorials.
Terraform Code: A simple Terraform module in your repository. For this example, we’ll use a basic module structure.
Here’s a sample Terraform module to get you started. Create a file named main.tf in your repository:
# main.tf
provider "aws" {
region = "us-west-2"
}
resource "aws_s3_bucket" "example" {
bucket = var.bucket_name
tags = {
Name = "My bucket"
}
}
variable "bucket_name" {
description = "Name of the S3 bucket"
type = string
}
output "bucket_arn" {
description = "ARN of the created S3 bucket"
value = aws_s3_bucket.example.arn
}
This module creates an AWS S3 bucket with a configurable name and outputs its ARN. Our goal is to generate documentation for this module automatically.
What is terraform-docs?
The terraform-docs tool is a popular open-source utility that scans your Terraform module and generates documentation in various formats, such as Markdown. It extracts details like variables, outputs, and resources, and formats them into a clean, human-readable table. For example, running terraform-docs markdown table . in your module directory might produce:
## Requirements
| Name | Version |
|------|---------|
| aws | >= 2.68 |
## Providers
| Name | Version |
|------|---------|
| aws | >= 2.68 |
## Inputs
| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| bucket_name | Name of the S3 bucket | string | n/a | yes |
## Outputs
| Name | Description |
|------|-------------|
| bucket_arn | ARN of the created S3 bucket |
We’ll use GitHub Actions to run terraform-docs automatically and update our README.md whenever we change our Terraform code.
Setting Up GitHub Actions for Terraform Documentation
GitHub Actions allows you to define workflows using YAML files stored in the .github/workflows directory of your repository. These workflows run in response to events, such as pushing code or creating a pull request. For our Terraform documentation, we’ll create a workflow that:
Triggers on pull requests or pushes to the main branch.
Runs terraform-docs to generate documentation.
Updates the README.md file and commits the changes.
Let’s break it down step by step.
Step 1: Create a GitHub Actions Workflow
In your GitHub repository, create a directory called .github/workflows and add a file named terraform-docs.yml. Here’s a sample workflow configuration:
name: Generate Terraform Docs
on:
pull_request:
branches:
- main
push:
branches:
- main
jobs:
docs:
runs-on: ubuntu-latest
steps:
# Check out the repository code
- name: Checkout
uses: actions/checkout@v3
with:
ref: ${{ github.event.pull_request.head.ref }}
# Generate Terraform documentation and update README
- name: Render Terraform Docs
uses: terraform-docs/gh-actions@v1.4.1
with:
working-dir: .
output-file: README.md
output-method: inject
git-push: "true"
Let’s unpack what this workflow does:
Name: The workflow is called “Generate Terraform Docs” for clarity.
Triggers (on): It runs when you push to the main branch or create a pull request against main.
Job (docs): The job runs on an Ubuntu runner (ubuntu-latest).
Steps:
The actions/checkout@v3 action checks out your repository’s code so the workflow can access it.
The terraform-docs/gh-actions@v1.4.1 action runs terraform-docs, generates documentation, and injects it into the README.md file. The git-push: "true" option automatically commits and pushes the updated README.md to the pull request branch.
Step 2: Configure Your README
To ensure terraform-docs injects the documentation correctly, your README.md should include markers where the generated content will be placed. Update your README.md like this:
# My Terraform Module
This module creates an AWS S3 bucket.
<!-- BEGIN_TF_DOCS -->
<!-- END_TF_DOCS -->
The <!-- BEGIN_TF_DOCS --> and <!-- END_TF_DOCS --> markers tell terraform-docs where to insert the generated documentation. Any content between these markers will be replaced each time the workflow runs.
Step 3: Commit and Test the Workflow
Commit the terraform-docs.yml and updated README.md to your repository.
Push the changes to the main branch or create a pull request.
Navigate to the Actions tab in your GitHub repository to see the workflow in action.
When the workflow runs, it will:
Generate documentation based on your Terraform module.
Update the README.md with a table of inputs, outputs, and other details.
Commit the changes to your pull request or branch.
You can check the workflow logs in the Actions tab to verify that everything ran successfully. Your README.md should now contain the generated documentation, like the Markdown table shown earlier.
How CI/CD Enhances Terraform Documentation
Now that we’ve set up the workflow, let’s explore how CI/CD makes this process powerful:
Automation on Every Change: The CI/CD pipeline triggers whenever you push code or create a pull request, ensuring your documentation is always up-to-date without manual intervention. For example, if you add a new variable to main.tf, the workflow automatically regenerates the documentation.
Visibility and Collaboration: By integrating documentation updates into pull requests, team members can review changes to both the Terraform code and its documentation in one place. This promotes collaboration and reduces errors.
Consistency Across Modules: If your repository contains multiple Terraform modules (e.g., in subdirectories), you can configure the working-dir parameter in the terraform-docs/gh-actions action to process them all. For example:
with:
working-dir: module1,module2,module3
This ensures consistent documentation across your project.
Reduced Human Error: Manual documentation updates are prone to mistakes, like forgetting to document a new output. The CI/CD pipeline eliminates this by generating documentation directly from the code.
Scalability: As your project grows, maintaining documentation manually becomes unsustainable. A CI/CD pipeline scales effortlessly, handling documentation for dozens or hundreds of modules with minimal configuration.
Best Practices for Terraform Documentation with GitHub Actions
To make the most of your CI/CD pipeline, follow these tips:
Use Specific Versions: Pin the terraform-docs/gh-actions version (e.g., v1.4.1) to avoid unexpected changes in behavior. Update it intentionally when needed.
Customize Output: The terraform-docs tool supports various flags to tailor the output. For example, you can add --sort-by required to sort variables by whether they’re required. Pass these flags in the workflow:
with:
args: --sort-by required
Secure Your Workflow: Ensure your workflow has minimal permissions. The default configuration above only needs read/write access to the repository, which is safe for documentation tasks.
Test Locally First: Install terraform-docs locally (instructions at terraform-docs.io) to test your documentation output before automating it. Run terraform-docs markdown table . to preview the result.
Document Multiple Modules: If your repository has multiple modules, use the find-dir parameter to scan subdirectories recursively:
with:
find-dir: modules/
recursive: "true"
Troubleshooting Common Issues
As a beginner, you might encounter a few hiccups. Here’s how to handle them:
Error: “terraform-docs: command not found”: This shouldn’t happen with the GitHub Action, as it includes terraform-docs. If you’re testing locally, ensure terraform-docs is installed and added to your PATH.
Documentation Not Updating: Check that your README.md has the <!-- BEGIN_TF_DOCS --> and <!-- END_TF_DOCS --> markers. Also, verify that the workflow ran successfully in the Actions tab.
Workflow Fails: Review the workflow logs in GitHub Actions for error messages. Common issues include incorrect YAML syntax or missing permissions. Ensure the workflow has write access to push changes.
No Changes Committed: If git-push: "true" isn’t working, confirm that the pull request branch is checked out correctly using actions/checkout@v3.
Conclusion
Automating Terraform documentation with GitHub Actions is a fantastic way to streamline your Infrastructure as Code workflow. By leveraging CI/CD, you ensure that your documentation is always accurate, saving time and improving collaboration. With just a few lines of YAML, you can set up a pipeline that generates and updates documentation whenever your Terraform code changes.
As you grow in your DevOps journey, this foundation will help you tackle more complex automation tasks. Experiment with the workflow, explore the terraform-docs documentation, and share your modules with confidence, knowing their documentation is top-notch.
For more details, check out the official terraform-docs GitHub Action documentation at terraform-docs.io and the GitHub Actions guide at [docs.github.com/en/actions]. Happy automating!
Sources: This article draws inspiration from the terraform-docs GitHub Action documentation and community examples, such as those found in the DEV Community and HashiCorp’s tutorials.
Subscribe to my newsletter
Read articles from Akinola Matthew directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Akinola Matthew
Akinola Matthew
Writing about Python, Django, Networking, and DevOps. A passionate and adept Software and DevOps Engineer.