Skip to content

Infrastructure as code: Terraform, testing and change review

B2Bnetwork team · · 7 min

Integrations, data and cloud

In brief

Infrastructure as code means that networks, machines, databases, and permissions are described in files in a repository, and changes are applied by a tool, not by a person in a console. In Terraform, the most important decisions at the start are where state is stored, how to split into modules and environments, and the rule that every change goes through a pull request with a plan to review. On top of that come tests, policies in the CI pipeline, and regular drift detection.

What infrastructure as code is

In the manual model, an administrator creates resources in the cloud provider's console or in a virtualization panel. A year later nobody knows why a firewall rule looks the way it does, and rebuilding the environment after a failure depends on the memory of a few people.

Infrastructure as Code (IaC) turns these steps into a declarative description of the target state. Terraform reads configuration files, compares them with reality, and computes a plan: what to create, what to change, what to delete. Only an approved plan is executed. As a result:

  • every change has an author, a description, and a history in the repository;
  • test and production environments are built from the same code, so they differ only in parameters;
  • rebuilding an environment after a failure or in a new region means running code, not running a project;
  • an auditor gets the history of infrastructure changes without collecting evidence by hand.

Terraform state: the most important decision at the start

Terraform records in a state file which resources it manages and how they map to the configuration. Without state, it does not know what already exists. That is why the first decision in a project is where state lives and who has access to it.

Rules that work in practice:

  1. Remote state, not local. A state file kept on one person's laptop is asking for trouble. State is stored in a remote backend, for example in cloud object storage or in a HashiCorp service, with versioning and encryption.
  2. Locking during changes. The backend must lock the state for the duration of an operation, so that two people or two pipelines do not change it at the same time.
  3. Separate state per environment and area. Production and test have separate states, and large systems are divided further, for example network, databases, applications. A mistake in one does not destroy the rest, and the plan is computed faster.
  4. State is sensitive data. A state file can contain passwords, keys, and internal addresses in plain text. Access to it is restricted the same way as access to a secrets vault; more on this in the article Secrets in applications.

Modules and environments

A Terraform module is a set of resources described once and used many times with different parameters, for example “a PostgreSQL database with backup, monitoring, and a private network”. The platform team maintains modules that comply with company standards, and product teams assemble their environments from them. This is one of the foundations of platform engineering.

Good modules have versions, documented parameters, and sensible defaults, and they do not try to handle every possible case. A module with forty parameters is harder to test than two smaller modules.

Environments are usually separated into distinct directories or repositories, each with its own state, that call the same modules with different values. A module change then moves through the development, test, and production environments in turn, just like application code. This layout of environments described in code from day one is shown in the scenario cloud platform and DevOps for a payments fintech.

Change review: the plan in a pull request

The most important IaC practice is reviewing the plan, not just the code. The same line in the configuration can change one parameter or delete and recreate a database. That is why, for every pull request, the CI pipeline:

  • formats and validates the code (`terraform fmt -check`, `terraform validate`);
  • runs static analysis and security policies, for example a ban on public data stores or mandatory cost tags;
  • computes `terraform plan` and publishes its summary in the pull request;
  • after approval and merge, runs `terraform apply` of exactly that saved plan.

In the plan, the reviewer looks above all for “destroy” and “replace” operations. Deleting a resource in production should require a separate, deliberate approval. Access to production changes belongs to the pipeline, not to people: personal accounts have read-only permissions in the cloud, apart from the emergency procedure.

The same review is a good place to control costs: an estimate of a change's cost in the pull request helps catch oversized machines before they exist. More on this in the article FinOps: How to Keep Cloud Costs Under Control.

Infrastructure testing

Terraform has a built-in `terraform test` command that runs tests written in `.tftest.hcl` files. A test can run just the plan, without creating resources, or create resources in a test environment, check the conditions, and delete them. An example of a plan-level test:

run "bucket_name_follows_standard" {
  command = plan

  assert {
    condition     = startswith(aws_s3_bucket.logs.bucket, "company-")
    error_message = "The bucket name must start with the company- prefix"
  }
}

The test layers are similar to those in applications:

LayerWhat it checksWhen
Validation and static analysissyntax, types, known misconfigurationsevery commit
Policiescompany rules: encryption, tags, regions, no public accessevery pull request
Module tests on the planmodule logic with different parametersevery pull request
Tests that create resourceswhether resources really get created and workmodule change, overnight

Drift and the tool's license

Drift is the difference between the code and reality, usually after a manual change in the console during an incident. It is detected by running `terraform plan` regularly for each environment, for example every night, with an alert when the plan is not empty. Every drift ends either with the change being moved into the code or with it being rolled back.

When choosing a tool, there is one more decision to be aware of. In 2023, HashiCorp changed the Terraform license from open source to the Business Source License, and since then the community has developed OpenTofu, an open fork under the Linux Foundation. Both tools use the same configuration language but are diverging in features over time, so it is worth recording your choice of one of them, along with the version, in company standards.

Questions and answers

Is Terraform suitable for configuring servers?

Terraform is best at creating and changing resources: networks, machines, databases, permissions, clusters. Configuring the inside of a system, for example packages and files on a server, is a job for configuration management tools or for prebuilt machine and container images. A common split: Terraform creates the infrastructure, the image contains the system with the application, and logging in to a server by hand is not needed.

How do you bring existing, manually created resources under Terraform?

Terraform can import existing resources into state, and newer versions have `import` blocks in the configuration. With a large number of resources, it is worth doing this area by area, for example network first, then databases, and checking after each import that the plan is empty. An empty plan means the code describes reality exactly.

Who should have the right to run terraform apply in production?

Ideally only the CI pipeline, triggered after a pull request is approved by someone other than the author. People have read permissions, and emergency access is time-limited, logged, and reviewed after the incident. This setup also makes it easier to meet audit requirements, because every change leaves a trace in the repository.

How many tests does infrastructure code need?

Fewer than application code, but more than zero. Validation, static analysis, and policies should run for every pull request, because they are cheap and catch the most common errors. Tests that create resources are worth having for modules shared by many teams, where one mistake spreads to many environments at once.

What it looks like in a project

Connecting systems or moving them to the cloud? Talk to an architect.

Let's talk

Read more: Integrations, data and cloud