Go to content
Infrastructure

Five Essential Best Practices for Terraform Code

When you write Terraform configuration, you describe cloud infrastructure in code: VPCs, databases, security groups, and other resources. Terraform calls the cloud provider’s API to create or update those resources, and it records the result in a state file, a JSON document that maps every resource in your configuration to the real object the provider created. Terraform reads that state file on every run to decide what has changed and what to do next. If you lose the state file, let two people write to it at once, or let a secret slip into it, your infrastructure is at risk.

The five practices below are what production Terraform setups rely on to avoid those failure modes: store state remotely with locking, split state by environment and component, keep modules small and versioned, pin every version, and keep secrets out of both code and state. Each section gives you the concrete choice to make and the mechanism behind it, including a few counterintuitive ones, like why marking a value sensitive does not keep it out of the state file. The last section also covers how to run plan and apply safely in CI and how to detect drift, the gap between your code and what actually exists in the cloud.

Store state remotely, lock it, and split it

Decide where the state file lives before anything else. If you keep it on a laptop or in a Git repository, you will eventually lose it, and Terraform will no longer know which resources it manages. Store it in an encrypted, versioned S3 bucket with locking enabled, and never on a laptop or in Git. Remote state in S3 with locking

A lock prevents two concurrent terraform apply runs from writing to the same state file at once. Without it, a second terraform apply overwrites the first one’s changes and leaves the state out of sync with the real infrastructure. Terraform 1.11 and later can lock using the S3 bucket itself by setting use_lockfile = true; earlier setups use a DynamoDB table to hold the lock. Terraform state locking

Separate state files for each environment and component limit the blast radius, so a bad change or a corrupted state in staging never touches production. For production in particular, a separate AWS account per environment gives a stronger boundary than separate state files inside one account. Split state by environment and component

Terraform workspaces tempt you to skip the splitting. A workspace is a named state instance that shares one backend configuration (the storage Terraform writes state to) and usually one set of credentials, so dev, staging, and production all run through the same role and the same remote storage. Separate directories with separate backends and separate roles are easier to reason about and secure. Why workspaces are a weak environment boundary Before you lay out the repository, decide how it maps to environments, because that layout is the foundation for how you structure Terraform repositories for modules and environments.

Keep modules small, focused, and versioned

A module is a reusable block of Terraform configuration with its own inputs and outputs. Small, focused modules with a small set of typed, documented inputs and outputs are easier to change safely than one large module with dozens of feature flags. A caller can see exactly what it depends on and what it can pass in. Small modules with typed inputs and outputs If you are unsure whether a piece of configuration should be a module, start from the question of reuse and responsibility rather than file size; see when to use Terraform modules.

Shared modules need versioning. Tag them with Git tags or publish them to a private registry. Reference a specific version from each environment, so an upgrade is a deliberate step you review rather than an accidental side effect of pulling the latest code. Version modules with Git tags or a private registry

Two smaller habits keep module behavior predictable. Use ${path.module} for any file path inside a module, so Terraform resolves the path relative to the module’s own directory instead of the directory where you happen to run the command. For reusable modules, prefer separate resources such as aws_security_group_rule over inline blocks, because callers can extend and compose them more easily. And keep dependencies explicit: instead of a broad depends_on at the module level, expose specific outputs and depend on the exact value you need, so Terraform does not create ordering constraints you do not actually require. Predictable module paths and explicit dependencies

Pin versions and commit the lock file

Pin the Terraform version, the provider versions (the plugins that translate your configuration into API calls for each cloud), and the module versions your configuration uses. Commit .terraform.lock.hcl, the file Terraform writes that records the exact provider builds, so every machine and every pipeline run uses the same provider code. Pin versions and commit the lock file

For providers and modules, use pessimistic version pinning with the ~> operator. This allows patch updates while locking the major and minor version. A constraint like ~> 5.0 permits 5.1 and 5.0.2 but not 6.0, so you get critical fixes without surprise breaking changes. Pessimistic version pinning

Keep secrets out of code and state

Never commit secrets to Terraform files or .tfvars files. Store them in a vault such as AWS Secrets Manager or SSM Parameter Store, and grant the workload permission to read them at runtime instead of baking them into configuration. Store secrets in a vault, not in Terraform files

The counterintuitive part is sensitive = true. That flag hides a value from CLI output and diffs, but it does not prevent the value from being stored in the state file, and state files can hold plaintext secrets. Treat the state file as sensitive data no matter what flags you set. Why sensitive values still land in state

Newer Terraform versions give you a way to keep supported secrets out of state entirely. Terraform 1.10 introduced ephemeral values, and Terraform 1.11 introduced write-only arguments, both of which keep secret values out of state and plan files. Write-only arguments require provider support: the AWS provider needs v5.88.0 or later for secret_string_wo, and the AzureRM provider needs v4.23.0 or later for Key Vault’s value_wo. Write-only arguments keep supported secrets out of state

Run plan in CI, review applies, and detect drift

The apply step is where damage happens, so route it through a reviewed pipeline. Run terraform plan in CI and apply only through that pipeline, using OpenID Connect (OIDC) and short-lived IAM roles instead of long-lived access keys. Enforce a Git workflow with no direct push to main, merge only through pull requests with approvals, never use auto-approve in terraform apply, and restrict write access in production to the pipeline role. Reviewed pipeline with OIDC and no auto-approve

Add quality and security checks to the pipeline before the apply. Tools such as tflint, checkov, and tfsec catch syntax errors, enforce style, and scan for security issues in your configuration, and you can test Terraform modules before release to catch behavioral problems early. Lint, scan, and test in the pipeline

Drift is the silent failure mode. Run terraform plan -detailed-exitcode on a schedule; an exit code of 2 means the real infrastructure no longer matches your code. Scheduled plan with a distinct drift exit code But keep the limits of plan in mind: plan is a reconciliation tool, not a monitoring tool. It only sees resources Terraform knows about, so anything created outside Terraform is invisible to it, and every field you add to ignore_changes is a field you can never detect drift on again. Pair scheduled plans with cloud-native asset inventory such as AWS Config and policy engines such as OPA or Conftest to catch drift and semantic violations that plan cannot express. Plan alone misses out-of-band resources and ignore_changes drift

More in Infrastructure Back to top ↑