OpenTofu conventions#
The language is still HCL and the files are still .tf, so the directory is still terraform/. The CLI is tofu (ADR-0015).
Consistency rules for this repository, and the reasoning where it is not obvious. CI enforces most of it, because a convention that relies on reviewer memory is a suggestion.
Versions#
| Thing | Pin | Why |
|---|---|---|
| OpenTofu CLI | ~> 1.13.0 (CI: 1.13.2, checksum-pinned) | Pinning the minor stops a 1.14 release changing behaviour under CI. Renovate tracks the CI pin; see CI tools for its checksum. |
| AWS provider | Modules: ~> 6.57, >= 6.57.1. Root modules: ~> 6.73. | 6.57.0 shipped a regression. The >= excludes it explicitly, and renovate.json refuses to propose it. The roots narrow the range to what is actually tested. |
archive provider | ~> 2.7 | Packages the Lambda source. |
http provider | ~> 3.5 | Used only by the check blocks that probe the live site. |
.terraform.lock.hcl is committed. It records provider checksums from registry.opentofu.org for Linux and macOS on amd64 and arm64, which makes it a supply-chain control rather than a convenience. Regenerate with tofu providers lock -platform=linux_amd64 -platform=linux_arm64 -platform=darwin_amd64 -platform=darwin_arm64.
CI tools#
Everything third-party that CI runs is pinned immutably (principle 5): Actions to a commit digest, with the version in a comment, and downloaded tools to the SHA-256 of the release archive. make pins fails the build if either slips, or if a workflow grants permissions anywhere but on a job.
| Tool | Version | Pinned in | Checksum file's signature |
|---|---|---|---|
| OpenTofu | 1.13.2 | .github/actions/setup-tofu/action.yml, used by every job that runs tofu | Sigstore, OpenTofu's release workflow |
| TFLint | 0.66.0 | terraform-plan.yml, the checksums input of setup-tflint | Sigstore, TFLint's release workflow |
| Trivy | 0.76.2 | terraform-plan.yml, TRIVY_SHA256 | Sigstore, Trivy's release workflow |
| gitleaks | 8.29.0 | terraform-plan.yml, GITLEAKS_SHA256 | None found |
| terraform-docs | 0.20.0 | terraform-plan.yml, TERRAFORM_DOCS_SHA256 | None found |
The TFLint AWS ruleset is pinned to a version in .tflint.hcl, and tflint --init verifies its signature itself. Trivy runs with --skip-check-update, so its rules are the ones built into the pinned binary and change only when its version does. The same reasoning keeps the TFLint ruleset from floating.
Changing a version. Renovate is configured to propose new versions, but it cannot compute a checksum, so its pull request fails CI until a person supplies one. That is deliberate. Download the release's checksums file and its signature (a .sig and .pem pair, or a .sigstore.json bundle), and check that the signature names the project's own release workflow:
cosign verify-blob tofu_1.13.2_SHA256SUMS \
--signature tofu_1.13.2_SHA256SUMS.sig \
--certificate tofu_1.13.2_SHA256SUMS.pem \
--certificate-identity-regexp '^https://github\.com/opentofu/opentofu/\.github/workflows/release\.yml@' \
--certificate-oidc-issuer https://token.actions.githubusercontent.com
For a bundle, pass --bundle in place of --signature and --certificate. Where a project publishes no signature, say so in the pull request. Then take the line for the Linux amd64 archive, and change the version and the checksum in the same commit.
An Action needs no checksum, because its commit digest is already immutable. Renovate is configured to update the digest and the version comment together. The pre-commit hooks are pinned the same way, with the tag in a frozen: comment; pre-commit autoupdate --freeze updates both.
Layout#
terraform/
├── seed/ # phase 0: once per account, via seed-account (ADR-0016)
├── bootstrap/ # phase 1: CI roles, applied by bootstrap-account
├── environments/prod/ # the only root module; S3 backend
│ ├── main.tf # module composition, nothing else
│ ├── checks.tf # post-apply assertions
│ ├── variables.tf
│ ├── outputs.tf
│ ├── providers.tf # provider config + locals
│ ├── versions.tf # required_* + backend
│ ├── terraform.tfvars # non-sensitive config, committed
│ └── tests/ # *.tftest.hcl
└── modules/<name>/
├── main.tf # or split by concern: s3.tf, cloudfront.tf
├── variables.tf
├── outputs.tf
├── versions.tf
└── README.md # prose + generated reference table
File names describe content, not type: s3.tf and cloudfront.tf in a module large enough to warrant splitting, rather than one 600-line main.tf.
Naming#
- snake_case for everything: resources, variables, outputs, locals. Enforced
by tflint.
- Resource labels describe the role, not the type.
aws_s3_bucket.site, not
aws_s3_bucket.site_bucket. The type is already in the address.
thisfor the single primary resource in a module —
aws_cloudfront_distribution.this.
- Physical names come from
var.name_prefix(${project}-${environment}). The
CI apply role is scoped to testz-*, so drifting from the prefix produces an authorization failure rather than a mystery.
Variables#
Every variable has a type and a description. tflint fails the build otherwise, because the module READMEs are generated from those descriptions.
Descriptions explain why, not what. "CloudFront price class" is useless; the reader can see that from the name. Say what the tradeoff is and what happens if it changes.
validation blocks are used for anything with a knowable constraint:
variable "log_retention_days" {
description = "..."
type = number
default = 14
validation {
condition = contains([1, 3, 5, 7, 14, 30, ...], var.log_retention_days)
error_message = "log_retention_days must be one of the retention periods CloudWatch Logs accepts."
}
}
Catching it at plan time beats an opaque API error four minutes into an apply.
Preconditions, postconditions, checks#
Three tools with different jobs, and using the wrong one is a common mistake:
validation— a constraint on a single variable, known before anything runs.precondition— a constraint involving data or other resources, checked
before that resource is created. Used for the "KMS key must be in us-east-1" assertion, which needs a data source.
check— a post-apply assertion, which reports a warning rather than
an error. This is the right tool for "the site actually responds and serves the right headers", because a failing probe should tell you something is wrong without wedging the pipeline or rolling back a change that was fine.
check blocks are the piece that closes the gap between "the API accepted my configuration" and "the thing works". See terraform/environments/prod/checks.tf.
Tagging#
Via provider default_tags only. No module contains tag-merging plumbing.
default_tags {
tags = {
Project = var.project
Environment = var.environment
ManagedBy = "terraform"
Repository = var.github_repository
}
}
A per-resource tags block is added only for a Name, and only where the console is otherwise unhelpful.
Modules#
- No remote module sources. Every module is local, in this repository. For a
project this size, a registry module is a dependency to audit and pin in exchange for saving thirty lines.
- No
countfor conditional single resources wherefor_eachreads better —
but count = var.enabled ? 1 : 0 is fine and used consistently for feature flags. Access those with one() rather than [0] in outputs, so disabling the feature does not produce an index error.
- Outputs are the interface. A module never reaches into another module's
resources; the root module wires outputs to inputs.
- Cycles are resolved at the root, visibly. The
aws_lambda_permission
trusting the distribution lives in main.tf rather than inside edge-api, because it needs the distribution ARN while the distribution needs edge-api's outputs. Putting it at the root makes the ordering explicit instead of subtle.
Testing#
Native tofu test with mock_provider, so the whole suite runs with no AWS credentials and no API calls — on every pull request, including from forks, in well under a minute.
The tests assert decisions, not plumbing: that mail is locked down, that wildcard issuance is forbidden, that TLS 1.3-only is still set, that access logs are off, that only main can hold a role that writes. Precisely the class of thing a reviewer skims past and a refactor quietly breaks. The last of those loads terraform/bootstrap and terraform/seed as modules from the production root's suite, so one tofu test covers the CI roles too.
Most suites load one module through a run block's module source and test it mostly at its defaults. That cannot see what the production root decides for itself: an argument main.tf hard-codes, such as enable_email_lockdown, or the way it passes a variable on. production.tftest.hcl closes that gap. It plans the production root itself, with its terraform.tfvars, and asserts the decisions as production makes them: TLS 1.3 only, IPv6, no access logs, no WAF, a private origin, a signed zone with its probe, and the mail lockdown down to the published DMARC tags (ADR-0023). Two rules keep it honest:
- A test file sets no variable that
terraform.tfvarssets. A value in a
test file's variables block wins over terraform.tfvars, silently. The production suite sets only the two values kept out of the file (alert_email, permissions_boundary_arn), as placeholders.
- **The production root's variables that
terraform.tfvarssets have no
defaults.** If the file were not loaded, the suite would stop on a missing value instead of testing something production does not use.
tofu test also passes terraform.tfvars values to a module run when the module has a variable of the same name, so the module suites see some of production's values too. That is a side effect of matching names, and no test relies on it.
Assertions read outputs, and outputs are read back from the planned resources rather than restated, so a test can fail when the configuration changes. The edge's security_posture is the example: it is what the website publishes, and posture_follows_the_configuration checks that it moves when the configuration does. Each assertion added or changed for ADR-0023 was shown to fail on the bad configuration it exists to catch.
The first piece of logic that is code rather than configuration, the DNSSEC probe's verdict, has standard-library Python unit tests (make test-probe): the wire format, which answers count as votes, and the quorum. They include the rules most able to fail silently, such as a SERVFAIL never being retried into a pass (ADR-0020). The drift verdict, which decides whether a saved plan shows drift, has the same kind of tests (make test-drift), chiefly that a failed or unexplained plan is never judged clean (ADR-0021). The external health check, scripts/health-check.sh, is tested by running it against stub servers on the local machine (make test-health): a homepage that is not HTTP 200 fails, an accepted TLS 1.2 handshake fails, and a host that cannot be reached is never counted as refusing TLS 1.2 (ADR-0022). Its DMARC and DKIM checks read the records as tags, so p=none; sp=reject fails and a real DKIM key does not pass as a revoked one (ADR-0023).
override_data is used where a mocked data source would break a precondition — overriding the region is more honest than deleting the assertion to make a test pass.
What CI enforces#
make check # pins, fmt-check, validate, lint, scan, secrets, test, test-probe, test-drift, test-health
make docs-check
make pins— every Action and pre-commit hook pinned to a commit, every
download checked against a checksum, no permissions granted at workflow level, and no checkout that leaves the job's token on disk.
tofu fmt -check -recursive— no formatting debates.tofu validateon every module and root.tflintwith the AWS ruleset, plus the naming and documentation rules.trivy configfor IaC misconfigurations, with the checks built into the
pinned binary, evaluated with the production root's terraform.tfvars.
gitleaksover the full history.tofu test, the probe's unit tests (make test-probe), the drift
verdict's (make test-drift), and the health check's (make test-health).
terraform-docsstaleness check — if a variable description changed and the
README was not regenerated, the build fails. This is the mechanism that keeps documentation living rather than aspirational.
Things deliberately not used#
- Workspaces. One environment, one state key. Workspaces make the
"which one am I in" failure mode too easy.
terraform_remote_state. The bootstrap layer's outputs are passed in as
variables instead, so the environment layer needs no read access to another state file.
- Terraform Stacks. HCP Terraform only, so not available with OpenTofu.
The three layers here (seed, bootstrap, prod) are ordered by workflows instead.
local-exec/null_resource. Nothing here needs to shell out. Where
imperative work is genuinely required, it is a CI step where it is visible.