DevOps

Infrastructure as Code with Terraform: Benefits and How to Get Started

Infrastructure as code turns servers and networks into reviewed, repeatable files. Here is how Terraform works, what to watch out for and a step-by-step way to start.

  • DivTech editorial team
  • 7 min read
01Write02Init03Plan04Review
DevOps · part 4 of 5

In many companies the production environment was built by hand, one console click at a time, by someone who may no longer work there. Nobody is quite sure which settings matter, staging drifted away from production long ago, and rebuilding after a disaster would be guesswork. Infrastructure as code (IaC) fixes this by describing servers, networks, databases and permissions in files that live in version control and are applied by a tool.

Terraform is the most widely used tool for this across clouds. This guide explains how it works, the practices that matter, the alternatives, and a low-risk way to get started. It is a regular part of our DevOps consulting and cloud consulting work.

What infrastructure as code means

There are two styles. Imperative scripts list steps: create this server, then attach this disk. Declarative tools describe the end state: there should be two servers of this size behind this load balancer. The tool works out what to create, change or delete to get there. Terraform is declarative, which makes the same file safe to apply repeatedly.

Terraform configurations are written in HCL, a readable configuration language. Providers connect Terraform to platforms such as AWS, Azure, Google Cloud, Cloudflare, Kubernetes or GitHub. Resources are the things you manage: a virtual network, a database, a DNS record, a role.

Why it is worth the effort

  • Repeatable environments: staging and production come from the same code with different variables, so they stay alike.
  • Review before change: infrastructure changes go through pull requests, just like application code.
  • Audit trail: version history shows who changed what and why, which helps with security reviews and compliance in sectors such as healthcare.
  • Faster recovery: an environment described in code can be recreated in a new region or account far faster than from memory.
  • Less key-person risk: the knowledge lives in the repository, not in one engineer's head.

How Terraform works

processThe Terraform change workflow
  1. 01Write

    Describe the desired infrastructure in .tf files on a feature branch.

  2. 02Init

    terraform init downloads the pinned providers and connects to the remote state backend.

  3. 03Plan

    terraform plan compares the code with state and real infrastructure and lists every create, change and destroy.

  4. 04Review

    Open a pull request with the plan attached; a teammate checks it, especially anything marked for destruction.

  5. 05Apply

    After merge, the pipeline runs terraform apply on the reviewed plan.

  6. 06Detect drift

    A scheduled plan reports differences between the code and what actually exists.

DivTech System

State: the part to get right first

Terraform records what it manages in a state file that maps your configuration to real resource IDs. Losing it, corrupting it or letting two people write to it at once causes serious problems. Store state in a remote backend such as an S3 bucket, Azure Storage or Google Cloud Storage, or a managed Terraform service, with encryption, versioning and locking turned on. Never commit state to Git: it can contain secrets such as database passwords in plain text.

Modules: reuse without copy-paste

A module is a reusable bundle of resources with inputs and outputs, for example a standard web service with its load balancer, autoscaling and alarms. Modules let a small team give every service the same secure defaults. Keep them small and focused, version them, and pin both module and provider versions so an upstream release cannot change your infrastructure unexpectedly.

Environments differ through variables, not through copied code. Production might use larger instances, more replicas and stricter backup retention, but it should be built from the same modules as staging. Terraform workspaces can separate environments too, but many teams find a separate folder and state per environment easier to reason about and to protect with different access rights. Whichever you choose, make it obvious from a plan which environment is about to change.

stackA typical Terraform repository structure
L1
Environment roots

One folder per environment (dev, staging, production) with its own variables and state.

L2
Your composition modules

Building blocks such as web-service, database or network that encode your standards.

L3
Registry or shared modules

Well-maintained community modules, pinned to exact versions.

L4
Providers

Cloud and SaaS providers, pinned with a lock file committed to the repository.

L5
Remote state backend

Encrypted, versioned, locked storage for each environment's state.

Separate state per environment so a mistake in dev can never touch production.

DivTech System

Reviewing changes through pull requests

The pull request is where IaC pays off. Have the pipeline post the plan output on every pull request so reviewers see the real effect, not just the diff in the code. Add automated checks before a human looks: terraform fmt and validate, a linter such as tflint, and a policy or security scanner such as Checkov or Trivy to catch public storage buckets, open security groups or missing encryption. Apply only from the pipeline, using credentials that individual developers do not hold. The same pipeline principles are covered in our CI/CD pipeline guide.

Drift: when reality and code disagree

Drift happens when someone changes infrastructure outside Terraform, usually a quick console fix during an incident. The next apply may silently undo it, or fail. Run a scheduled plan, for example nightly, and alert when it shows changes. When drift appears, decide whether the code or the live change is right: update the code to match, or let Terraform revert the change. Over time, reduce drift at the source by limiting console write access in production to emergency break-glass roles.

Terraform alternatives

ToolLanguageCloudsWorth knowing
TerraformHCLMulti-cloudLargest provider ecosystem; HashiCorp moved it to the Business Source License in 2023, so check the terms against your use
OpenTofuHCLMulti-cloudOpen-source fork of Terraform under the Linux Foundation, largely compatible with existing configurations
PulumiTypeScript, Python, Go, C#, JavaMulti-cloudUses general-purpose languages, which suits developer-heavy teams but allows more complexity
AWS CloudFormationYAML or JSONAWS onlyNative to AWS with no separate state file to manage; the AWS CDK generates it from code
Azure BicepBicepAzure onlyNative, concise language for Azure resources

For teams that use more than one provider, or expect to, a multi-cloud tool avoids learning several. Our article on multi-cloud vs hybrid cloud covers when that situation genuinely arises.

How to get started

timelineA low-risk path to infrastructure as code
  1. Week 1Foundations

    Choose the tool, set up the remote state backend with locking, and agree a repository layout.

  2. Weeks 2-3First slice

    Codify something non-critical, such as a dev environment or DNS, and import existing resources with import blocks.

  3. Weeks 4-6Pipeline

    Plan on every pull request, apply on merge, add formatting, linting and security checks.

  4. Months 2-3Expand

    Extract modules, bring staging and production under code, and restrict manual console changes.

Indicative timeline for a single cloud account; larger estates are usually migrated in waves.

DivTech System

Common mistakes to avoid

  • One giant state file for everything. A single plan that touches every resource is slow and risky. Split state by environment and by area, such as network, data and applications.
  • Unpinned versions. Floating provider and module versions mean the same code can produce a different plan next week.
  • Applying from laptops. When engineers run apply locally with powerful credentials, review is optional in practice. Apply from the pipeline only.
  • Copy-pasted environments. Duplicating folders for each environment invites drift between them. Use shared modules with environment-specific variables.
  • Over-abstracted modules. A module with dozens of optional inputs becomes harder to understand than the resources it wraps. Prefer a few opinionated modules.

Do not try to import everything at once. Bring resources under management in groups, check that the plan shows no changes after each import, and keep a list of what remains. Pair this work with the security basics in our guide to cloud security best practices, and with containers if you use them, as described in Docker vs Kubernetes. Databases deserve particular care; our database and cloud transformation team often handles that part.

DivTech helps teams move from hand-built environments to reviewed, reproducible infrastructure without disrupting production. Request a quote and we will propose a first slice to codify.

Frequently asked questions

Is Terraform still free to use?

Terraform's source is available under the Business Source License, which permits most internal use but restricts some competitive commercial uses. Read the licence for your situation, or use OpenTofu, an open-source fork with a largely compatible language.

Can Terraform manage infrastructure that already exists?

Yes. You write configuration that matches the existing resource and import it into state, either with the import command or with import blocks in newer versions. After importing, a plan should show no changes.

Terraform or CloudFormation for an AWS-only company?

Both work. CloudFormation is native and needs no separate state store. Terraform or OpenTofu suit teams that also manage other providers, such as DNS, monitoring or a second cloud, with one tool and one workflow.

How do we keep secrets out of Terraform code?

Reference secrets from a secrets manager or vault instead of writing them in .tf files, mark sensitive variables as sensitive, and protect the remote state, because state can still contain secret values.

  • Infrastructure as code
  • Terraform
  • DevOps
  • Cloud

free consultation

Need help with devops?

Talk to our DevOps Consulting team. We'll review your situation and suggest a practical next step, free.