On this page
The short answerWhat goes stale in Terraform docsExtract the examples firstCheck formattingInitialize without a backend, then validateLint what validation does not seeTest the logic with terraform testPlan for real, in a credentialed laneKeep the README tables honestTest the copies in your guidesKeep credentials out of the runRun it on every changeChecklist for a Terraform example testWhere DocsAlive fitsWhat this does not replaceThe sources we checkedFAQTerraform docs are full of configuration blocks, init and plan commands, variable tables and sample output. A module README says which inputs to set and which outputs to expect; a quickstart says which commands to run in which order. Each of those can drift while the module keeps working: a provider renames an argument, a variable gains a required value, a command flag changes, and the page a reader copies from now fails on the first line. This guide shows how to catch that before readers do: extract every documented example, format-check and validate it without a backend, lint it, test the logic with Terraform's own test framework, and keep the generated input and output tables honest.
The short answer
Test a Terraform example in layers, because each layer catches a different failure, and the cheap layers need no cloud account at all. Extract every configuration block and command from the docs into files a tool can read. Check formatting with terraform fmt -check. Initialize without touching a backend using terraform init -backend=false, then run terraform validate to confirm the configuration is syntactically valid and internally consistent. Lint it with TFLint for the mistakes validation does not see. For the logic a module promises, write a .tftest.hcl file and run terraform test; with a mocked provider the test needs no credentials. Reserve terraform plan against a real account for the examples readers build on, in a separate credentialed lane. Finally, regenerate the module's input and output tables with terraform-docs and fail the run when the README no longer matches the code.
DocsAlive does not run terraform validate or terraform test for you, and it does not plan or apply anything in your cloud account. It reads the Markdown pages around the module — the README, the quickstart, the tutorial, the migration guide — and runs the code blocks it can run in a fresh container, so the shell commands a reader copies are exercised in page order. Keep the Terraform tooling described here for the configuration itself, and use an execution check for the prose pages readers follow. The installation docs guide covers the install steps that precede the first terraform init, and the config examples guide covers JSON, TOML and YAML snippets in the same spirit.
What goes stale in Terraform docs
Infrastructure code changes in small steps, and each step can break a different part of the documentation:
- Provider arguments. A resource argument is renamed, split in two, or removed in a newer provider release. The example still reads naturally, but it fails at validate time or silently does something different.
- Version constraints. The docs pin a provider or a Terraform version that no longer matches what the module supports. Readers install the version the page names and hit an error the maintainers fixed two releases ago, or they install the latest and hit one the page never mentioned.
- Variables and outputs. A variable is added without a default, a name changes, or an output is removed. The tables in the README still list the old interface, so a documented module call fails with a missing-argument error.
- Commands and flags. A quickstart tells the reader to run a sequence of commands, and one of them has a different flag, a different order, or a prompt that was not there before.
- Sample output. The plan output or the output values printed in the docs no longer look like what the tool prints, which makes a correct run look like a failure.
- Module sources and references. A documented source address, a registry path or a version tag points at something that moved.
- Backend and state assumptions. An example assumes a remote backend that a new reader does not have, so the first command fails for a reason unrelated to the example.
None of these need a reader to find them. Every one is visible to a validator, a linter or a test run, which is the point of testing the examples instead of proofreading them.
Extract the examples first
Every tool below works on files, so the first job is getting each documented example into one, unchanged. Pull each configuration block out of the docs into its own directory, keeping the page it came from in the directory name or a manifest. A directory per example matters because Terraform treats a directory as a module: two blocks that define the same resource name must not land in the same folder.
Most documented blocks come in two kinds. A complete example is a root module a reader could paste into an empty folder and run. A fragment shows one resource or one argument and assumes the rest. Decide for each fragment how it will be wrapped — usually with a terraform block that declares the required providers, a provider block, and any variables the fragment references — and record that wrapper separately from the extracted text. The wrapper is test scaffolding. The fragment itself must stay exactly as the docs print it.
Do not tidy the examples as you extract them. If a documented block is missing a closing brace, uses an attribute that does not exist or refers to a variable that is never declared, that is the finding. Extraction that silently fixes the text produces a test suite that passes and docs that still fail for readers. Extract mechanically, check what you extracted, and fix the docs — not the test copies — when something fails. Extract the shell commands the same way, in page order, because a documented sequence only means something in sequence.
Check formatting
Formatting is the cheapest check there is. The terraform fmt command rewrites configuration files into Terraform's canonical format, and in a test run you want it to report rather than rewrite. The -check flag does exactly that: the exit status is 0 when the input is properly formatted and non-zero otherwise, and the command lists the files that are not. Add -recursive to process subdirectories as well as the current one, and -diff to print the changes it would make:
terraform fmt -check -recursive -diff
A formatting failure in a documented example is rarely a reader-facing bug by itself, but it is a reliable signal that someone edited the block by hand without running the tooling that would also have caught a real mistake. Note that the canonical format may change in minor ways between Terraform versions, so after you upgrade Terraform, run terraform fmt over the docs examples along with the modules and commit the result in the same change.
Initialize without a backend, then validate
Validation needs an initialized working directory, with the referenced providers and modules installed. The terraform init command prepares that, and it is safe to run more than once. In a docs test you rarely want the example's backend configuration to take effect — it may point at remote state that does not exist for this run — so skip it: the -backend=false flag tells init to skip backend configuration, and the validate documentation names this exact form for initializing a directory for validation without accessing any configured backend. Run init non-interactively so a missing value fails the job instead of waiting for a prompt, then validate:
terraform init -backend=false -input=false
terraform validate
What validate checks is deliberately narrow. It verifies that a configuration is syntactically valid and internally consistent, regardless of any provided variables or existing state, which makes it a good check for attribute names and value types in reusable modules. It does not validate remote services, such as remote state or provider APIs. That limit is the useful part for docs testing: validate runs anywhere, on every change, with no account and no secrets, and a documented block that uses an argument the provider no longer has fails here, immediately.
For a machine-readable result, add -json. Terraform prints a JSON object describing the diagnostics, and the output includes a format_version key that you should read before parsing the rest. Use the JSON form when you want the failure to name the file and line of the offending block in a report. The documentation also warns that Terraform may hit an error before validation starts, and that output will not be JSON, so a script that consumes the output must treat a non-JSON result as a generic error instead of crashing on it.
Pin what you install. A docs test that picks up whatever provider version is newest tomorrow will pass today and fail tomorrow for reasons unrelated to the docs. Commit the dependency lock file for the example directories, or generate it with terraform providers lock, which adds provider selection information to the lock file without initializing the providers. When the docs name a version constraint, make the test install within that constraint, because the constraint is part of what the page promises. This also decides which side of a failure is wrong: if a documented example breaks only on the newest provider release, either the docs or the pinned range needs to change, and the run tells you which one drifted.
Lint what validation does not see
Validate answers whether the configuration is well formed. A linter answers whether it is a good idea. TFLint is a Terraform linter that inspects the files in the current directory by default, and takes --chdir to point at another directory or --recursive to walk a tree of them — convenient when each extracted example lives in its own folder. Its configuration lives in a .tflint.hcl file, where a plugin block turns on rulesets. The bundled Terraform ruleset is enabled with the recommended preset by default, and separate provider rulesets exist for Amazon Web Services, Microsoft Azure and Google Cloud. Download plugins once with --init, then run the linter:
tflint --init
tflint --recursive
Choose the output format to suit where the result goes. The -f option accepts default, json, checkstyle, junit, compact and sarif, so the same run can print a readable summary for a person and a JUnit or SARIF file for the CI system. For documentation the most useful findings are the ones about the language itself: deprecated syntax and unused declarations in an example teach readers a pattern you would not write today. Treat a lint error in a documented example like any other failing example, with the page and block named in the report.
Test the logic with terraform test
Validation and linting read the configuration. They do not run it. Terraform's test framework does, and it is the right tool for the promises a module makes: that this variable produces that resource name, that these outputs exist, that an invalid input is rejected. Tests live in files with the .tftest.hcl or .tftest.json extension. Terraform looks for them in the main configuration directory and in a tests directory by default, and you run them with terraform test from the root of the module. Each file holds one or more run blocks, and each run block contains assert blocks with a condition and an error_message. A minimal test of a documented example looks like this:
variables {
bucket_prefix = "test"
}
run "valid_string_concat" {
command = plan
assert {
condition = aws_s3_bucket.bucket.bucket == "test-bucket"
error_message = "S3 bucket name did not match expected"
}
}
The command attribute is the detail to get right. It is either plan or apply, and when you leave it out the default is a normal apply, which creates real infrastructure. The test command documentation carries an explicit warning that it can create real infrastructure that costs money, and that Terraform attempts to destroy what remains when a test file finishes and reports anything it could not remove. For a docs test, set command = plan wherever the claim you are checking is about configuration logic, and keep every apply-style test in the credentialed lane described below.
Tests can reference any named value in the configuration, and outputs from the current and earlier run blocks, so an assertion can check exactly what the docs claim an output will be. A variables block at the root of the file, or inside a run block, supplies the inputs the documented example uses; a value inside a run block overrides the file-level value for that run only, which lets one file test both the documented call and a deliberately bad one. The run block also accepts an expect_failures attribute for the case where the page promises that a certain input is rejected.
Each test file keeps its own state in memory, starting empty, separate from any existing state for the configuration, so running the command does not touch live infrastructure through state. The options that matter in CI are -filter to run specific test files, -test-directory to look somewhere other than tests, -verbose to print the plan or state for each run block, -json for machine-readable results, and -junit-xml to save a JUnit report to a path you choose:
terraform test -junit-xml=docs-tests.xml
Mock the provider so the test needs no credentials
From Terraform v1.7.0 onward, tests can mock providers, resources and data sources, so you can test parts of a module without creating infrastructure or holding credentials. A mock_provider block returns the same schema as the original provider and generates fake data for computed attributes, and from the perspective of a plan or apply inside a test file the mocked provider behaves like a real one that happens to create nothing:
mock_provider "aws" {}
run "sets_correct_name" {
variables {
bucket_name = "my-bucket-name"
}
assert {
condition = aws_s3_bucket.my_bucket.bucket == "my-bucket-name"
error_message = "incorrect bucket name"
}
}
This is the combination that makes documentation testing practical for infrastructure code. The documented module call runs through the real Terraform language engine, against the real provider schema, with no account and no cost — so a renamed argument, a missing required input or a wrong output name fails the test. What a mock cannot tell you is whether the real cloud accepts the values, which is the job of the next layer. If the module under test must run on older Terraform versions, say so in the docs and keep the mocked tests in a lane that uses a Terraform version that supports them.
Plan for real, in a credentialed lane
Some documented examples only mean something against a real account: the quickstart whose first command plans a network, the tutorial that ends with a running instance. Run those with terraform plan in a dedicated lane that has its own credentials, and keep it separate from the validation lane. Plan is useful because it includes an implied validation check and reports what Terraform would do. Two options matter in automation. -out=FILE saves the generated plan so the apply step runs exactly what was reviewed, which is the two-step workflow the plan documentation describes for automation. And -detailed-exitcode changes the exit codes so the result is machine-readable: 0 means the run succeeded with an empty diff, 1 means an error, and 2 means it succeeded with a non-empty diff.
terraform plan -detailed-exitcode -out=docs-example.tfplan
How to read those codes depends on what the page promises. A quickstart that starts from nothing should end its first plan with exit code 2, because it intends to create something; a page that claims the configuration is already converged should end with 0. Either way, 1 is a broken example. Do not run an apply-style check against an account that holds anything you care about. The testing documentation recommends dedicated testing accounts with the target providers that you can routinely purge, precisely so accidental and costly resources do not accumulate, and that advice applies to every credentialed docs run.
Keep the README tables honest
A module README usually carries a table of inputs and a table of outputs, and those tables are documentation that can be generated rather than maintained by hand. terraform-docs generates documentation from Terraform modules in several output formats, and the markdown table format is the common choice for a README. It takes the module path as an argument, can write into a file, and by default injects its output between a pair of comment markers so that the prose around it stays untouched:
terraform-docs markdown table --output-file README.md --output-mode inject .
The default markers are an opening and closing HTML comment, <!-- BEGIN_TF_DOCS --> and <!-- END_TF_DOCS -->, and the generated content goes between them. The other output mode, replace, overwrites the whole file instead. Settings can live in a .terraform-docs.yml file, which is the default configuration file name, so the same command runs the same way for everyone. For a docs test the useful option is --output-check, which checks whether the content of the output file is up to date. Run it in CI, and a pull request that changes a variable or an output without regenerating the README is caught before the table lies to a reader.
Generated tables solve the interface half of the problem. They do not cover the examples next to them: the usage block that shows a module call, the sample values, the command a reader pastes. Those still need the extraction and validation steps above, and a usage block that calls the module with an input name the table no longer lists is exactly the failure those steps exist to find.
Test the copies in your guides
The module README is not the only place a configuration block lives. The quickstart shows the first module call a new user pastes. The tutorial builds a configuration up over several pages. The migration guide shows the before and after of a renamed variable. The registry page repeats the README, and an examples directory in the repository holds fuller versions. Each copy was correct when it was pasted, and each one ages independently, so a provider change that the canonical example survives can still break the tutorial.
Extract and check the copies the same way as the canonical examples — the extraction step does not care which page a block came from. When a copy fails, fix the page, then search for the same block elsewhere. The documentation drift guide covers the general pattern: examples rarely live in one place, and testing only the canonical copy leaves the others to fail in front of readers. For the shell commands in a tutorial, the quickstart and tutorial testing guide describes running them in a clean environment, in page order.
Keep credentials out of the run
Infrastructure docs are one of the likeliest places for a real secret to slip into an example, and the test lane should be built so that cannot hurt you. Three rules keep it safe. First, the formatting, validation, lint and mocked-test lanes need no credentials at all, so run them in the plainest CI job you have, with no secrets in the environment. Second, the credentialed lane uses a dedicated testing account whose resources you can purge, with credentials held in the CI secret store and scoped to that environment — never a key copied from someone's machine, and never one taken from the docs. Third, scan the examples before you run them: if a documented block ships with an access key, a token, an account ID or a production address in it, that is a finding about the docs, and it should fail the run like any other error. The credentials in docs examples guide covers how to handle examples that genuinely need a key.
Variable files deserve the same care. Terraform loads values from several places, and a terraform.tfvars file committed next to an example is easy to forget. Keep the values an example needs in the example's own test variables, use obviously fake placeholders in anything that is published, and treat sensitive values as secrets that arrive from the environment at run time.
Run it on every change
- Pull requests: format-check, validate, lint and run the mocked tests on every change to the docs or the module. These checks are fast and need no account, so there is no reason for them to be rarer than the lint you already run. The pre-commit guide shows how to run the same checks before a commit leaves a laptop.
- Releases: run the full set — including the credentialed plan lane and a pass against the newest provider release — before the new version is announced, so the docs and the module change in the same step.
- Nightly: run validation and the mocked tests against the latest allowed provider versions even when nobody touched the docs. Providers change under docs that nobody edited, and the nightly run is what catches drift from the provider side. The GitHub Actions guide covers wiring these jobs into a workflow.
Whichever cadence you choose, the failure has to reach a person. A failing docs test that only colours a dashboard red will be failing, unread, on the day a reader finds the same break by hand.
Checklist for a Terraform example test
- Every configuration block and command extracted from the docs, unchanged, with its source page recorded and fragments wrapped separately.
terraform fmt -check -recursiverun over the examples.
terraform init -backend=falsefollowed byterraform validatefor every example, with provider and module versions pinned.
- TFLint run over the examples, with its plugins installed through
tflint --init.
- A
.tftest.hcltest for each behaviour the docs promise, withcommand = planunless the claim needs a real apply.
- Mocked providers used where a test needs no real account.
- Credentialed plans run in a dedicated lane against a purgeable testing account, with the exit code read according to what the page promises.
- README input and output tables generated with terraform-docs and checked with
--output-check.
- Copies in quickstarts, tutorials, migration guides and the registry page extracted and checked too.
- No real credentials in any example, and no secrets in the validation lane.
Where DocsAlive fits
The checks above cover the module and its configuration. They do not cover the pages around it — the quickstart whose first command every new user runs, the tutorial that spans four pages, the README in each repository that repeats the usage block. Those pages are Markdown, and their code blocks are where readers actually copy from. DocsAlive runs the code samples in your docs in a clean sandbox and reports what breaks: it installs DocsAlive as a GitHub App, runs the blocks, and opens fix PRs that a human approves. A free health check runs the samples on up to 40 pages of a public repo and sends a report within 2 business days — the quickest way to see where the copies in your guides stand. The docs testing checklist puts this execution layer next to the rest of the pre-release checks. If your infrastructure docs also cover Helm charts, the Helm docs testing guide applies the same layered approach.
What this does not replace
Documentation tests do not test the infrastructure. A configuration can validate, lint clean, pass its mocked tests and still create the wrong network, because correctness of the design is not something any of these tools can see. A mocked provider cannot tell you whether the real cloud will accept a value, and a plan is not an apply: it shows intent, not the outcome of the provider's real behaviour. Policy checks, security review and cost control sit outside all of this. And none of it checks the prose — a guide can have perfectly valid examples and still explain them badly. What these checks remove is the specific, common failure where the docs show a configuration the tools no longer accept, and they remove it before a reader finds it.
The sources we checked
| Source | What it covers |
|---|---|
| Terraform CLI documentation: fmt, init, validate, plan and test | The -check, -recursive and -diff options of fmt; -backend=false and -input for init; what validate does and does not check, and its JSON output; -out and -detailed-exitcode for plan; test files, the -filter, -test-directory, -verbose, -json and -junit-xml options, and the warning about real infrastructure |
| Terraform language documentation: tests and mocking | The .tftest.hcl and .tftest.json extensions, run and assert blocks, the command attribute and its default, variables, expect_failures, and mock_provider (Terraform v1.7.0 and later) |
| Terraform CLI documentation: providers lock | Writing provider selection information to the dependency lock file without initializing providers |
| TFLint README, configuration documentation and the Terraform ruleset rules list | The --init, --chdir, --recursive and -f options, .tflint.hcl, the bundled Terraform ruleset and its recommended preset, the deprecated-syntax and unused-declaration rules, and provider rulesets |
| terraform-docs documentation | The markdown table command, --output-file, --output-mode (inject and replace), --output-check, the default markers and .terraform-docs.yml |
| DocsAlive product pages | What the health check runs, the GitHub App, and human-approved fix PRs |
FAQ
Is terraform validate enough?
No. Validate confirms the configuration is syntactically valid and internally consistent, and it does not contact remote services or provider APIs. It will not tell you whether a plan succeeds against a real account, whether the module's logic produces the values the docs claim, or whether the README tables match the code. Formatting, linting, tests and a credentialed plan answer those separate questions.
Do I need cloud credentials to test documentation examples?
Not for most of it. Formatting, backend-free init, validate, TFLint and tests that use a mocked provider all run without an account. You need credentials only for the plan lane, where a real provider is asked to evaluate real values, and that lane should use a dedicated testing account.
My README tables are generated. Do I still need this?
The generated tables inherit the code's interface, but the usage blocks, quickstarts and tutorials around them are written by hand and do not update themselves. Generated tables also go stale when nobody reruns the generator, which is what the output check in CI is for. Test the handwritten examples at minimum.




