Before you write a single line of code it is worth understanding which problem you are solving. Terraform is not "yet another cloud scripting tool": it is a shift in how you think about creating, modifying and destroying infrastructure. In this lesson we start from a real, recognisable case — a company that built its entire platform by hand from its provider's web console — to see why that approach breaks down, what infrastructure as code (IaC) actually is, where Terraform sits within that ecosystem, and when you should not use it. This is the lesson that gives meaning to everything that follows.
- The EcoMarket case: infrastructure built by hand
EcoMarket is an online organic-products store. It started with two people, one server and plenty of enthusiasm. Today it has a four-person platform team and a modest but very real architecture:
- A web application,
ecomarket-web, served behind a load balancer. - A managed PostgreSQL database.
- An object storage bucket for product images.
- Three environments:
dev,stagingandprod, all in theeu-west-1region (Ireland).
All of that infrastructure was created by clicking around the cloud provider's web console. It worked for two years. These are the symptoms that pushed the team to reconsider:
| Symptom | What it looks like day to day at EcoMarket |
|---|---|
| Drift between environments | staging runs PostgreSQL 14 and prod runs 15. Nobody remembers why. A query that works in staging fails in production. |
| Undocumented changes | Someone grew the database disk on a Friday night during an incident. There is no record of who, when or why. |
No way to recreate prod |
The question "if we lose the region, how long does it take to bring production back up?" has no answer. Nobody knows the exact list of resources or their parameters. |
| Knowledge locked in one head | Only one person knows which firewall rules let the load balancer talk to the application. |
| No peer review | An infrastructure change goes through no review at all: you make it and that is that. There is no git log for the infrastructure. |
| New environments are painfully expensive | Creating a test environment for a demo costs a full day of manual work. |
| Manual copying errors | When the staging configuration was replicated into prod, automatic backups were left switched off. |
Notice that none of these problems is a fault of the cloud provider. They are all a consequence of the fact that the desired state of the infrastructure exists only in the web interface and in people's memories. There is no reviewable, versioned, reproducible source of truth.
That is exactly the gap infrastructure as code fills.
- What infrastructure as code (IaC) is
Infrastructure as code is the practice of defining and managing infrastructure resources (networks, machines, databases, buckets, permissions, DNS and so on) through versioned text files instead of manual actions in a graphical console.
What that buys you:
- Reproducibility: the same code applied twice produces the same result. EcoMarket could recreate
prodfrom scratch in minutes. - Versioning: the infrastructure lives in Git. You know who changed what, when and why (the commit message).
- Peer review: a change to the production database goes through a pull request, exactly like an application code change.
- Living documentation: the code is the documentation, and it never falls out of date with reality, because it is what actually runs.
- Automation: infrastructure can be deployed from a CI/CD pipeline (we cover this in module 8).
- Consistency across environments:
dev,stagingandprodare generated from the same code with different parameters, so drift becomes something you can detect.
One important nuance: IaC is not simply "having scripts". A bash script that calls the provider's CLI is automation, but it does not solve the problem of knowing what the current state is, nor that of converging towards the desired state. Point 4 turns on exactly that difference.
- What Terraform actually is
Terraform is an open-source tool created by HashiCorp that lets you define infrastructure in declarative text files and apply it across dozens of different platforms (AWS, Azure, GCP, Kubernetes, GitHub, Cloudflare, databases, monitoring systems and more).
In one sentence: Terraform reads your description of the desired state, compares it with the real state it has recorded, works out the minimum set of operations needed and executes them through the providers' APIs.
Its defining characteristics:
- Declarative: you describe the what, not the how.
- Provider-agnostic: one language (HCL) and one workflow for any platform that has a provider. That does not mean the code is portable between clouds — AWS and Azure resources are different — but that the workflow is identical.
- Explicit state: it keeps a state file that maps the objects in your configuration to the real objects on the platform.
- Dependency-graph driven: it understands that the load balancer needs the network before it can exist, and orders the operations for you.
- Change preview:
terraform plantells you exactly what is going to happen before it happens. This is probably the feature that brings a platform team the most peace of mind.
A minimal example so you can see the shape of the language (the syntax is studied in depth in module 2; here just look at the structure):
# A "resource" block describes an object Terraform must create and maintain.
# - "random_pet" is the resource TYPE (contributed by the "random" provider).
# - "suffix" is the LOCAL NAME we give it inside our own code.
resource "random_pet" "suffix" {
length = 2
separator = "-"
}
# This resource writes a file to disk. Notice how its content
# references the previous resource: Terraform works out on its own that it
# must first create "random_pet.suffix" and only then this file.
resource "local_file" "inventory" {
filename = "${path.module}/ecomarket-inventory.txt"
content = "project=ecomarket suffix=${random_pet.suffix.id}\n"
}Two ideas already show up here, and they will stay with you for the whole course:
- There is no written execution order. You never say "first create the suffix, then the file". Terraform infers it from the
random_pet.suffix.idreference. - There are no existence checks. You do not write "if the file already exists, do not create it". Terraform knows whether it exists because it has it in its state.
- Declarative versus imperative
This distinction is the hardest one to internalise for anyone coming from scripting. Let us look at it with a single goal: EcoMarket wants exactly three inventory files, one per environment.
Imperative approach (a script that describes steps):
#!/usr/bin/env bash
# Imperative approach: we describe HOW to reach the result.
set -euo pipefail
for environment in dev staging prod; do
file="ecomarket-${environment}-inventory.txt"
# We have to check the current state ourselves...
if [ -f "$file" ]; then
echo "$file already exists, updating it"
else
echo "Creating $file"
fi
echo "environment=${environment}" > "$file"
done
# ...and if tomorrow we drop "staging" from the list, the staging file
# will stay there forever: the script has no idea what it created in previous runs.Declarative approach (a description of the desired result):
# Declarative approach: we describe WHAT must exist.
variable "environments" {
default = ["dev", "staging", "prod"]
}
resource "local_file" "inventory" {
for_each = toset(var.environments)
filename = "ecomarket-${each.key}-inventory.txt"
content = "environment=${each.key}\n"
}
# If tomorrow we drop "staging" from the list, Terraform WILL PLAN ITS DESTRUCTION,
# because it knows that file exists and is no longer part of the desired state.The key difference is not the syntax but who has to reason about the current state:
| Aspect | Imperative (scripts, CLI) | Declarative (Terraform) |
|---|---|---|
| What you describe | The sequence of steps | The desired end result |
| Who computes the differences | You, by hand, with conditionals | The Terraform engine |
| Running it twice | May duplicate or fail | Idempotent: the second run does nothing |
| Removing something from the code | Has no effect | Its destruction is planned |
| Previewing the effect | No, unless you program it yourself | Yes, with terraform plan |
| Initial learning curve | Low | Medium (you have to understand state) |
An honest caveat: Terraform is declarative, but not "magically declarative". The state file is precisely what makes that magic possible, and managing it well is the subject of module 3. When someone says Terraform is complicated, they are almost always talking about state.
- Conceptual architecture: core, providers and state
Terraform is made up of three conceptual pieces. Here you get the overview; the precise vocabulary arrives in the lesson Terraform Core Concepts.
flowchart LR
subgraph You["EcoMarket platform team"]
A[".tf files<br/>(desired state)"]
end
subgraph Core["Terraform core"]
B["HCL parser"]
C["Dependency graph"]
D["Diff engine"]
end
E[("State<br/>terraform.tfstate")]
subgraph Prov["Providers (plugins)"]
F["aws"]
G["random"]
H["local"]
end
I["Real APIs<br/>(AWS, file system...)"]
A --> B --> C --> D
E <--> D
D --> F & G & H
F & G & H --> I
- The core: the
terraformbinary. It reads the configuration, builds the dependency graph, compares the desired state with the recorded state and decides which operations to run. It knows nothing about AWS or any other specific service. - The providers: independent plugins that translate the core's intentions into calls to a specific API. The
awsprovider knows how to create an EC2 instance; thelocalprovider knows how to write a file. They are downloaded automatically byterraform initfrom the Terraform Registry. - The state: a JSON file that records the correspondence between each resource in your configuration and the real object. Without it, Terraform could not know whether
ecomarket-prod-dbalready exists or has to be created.
This separation explains why Terraform covers so many platforms: anyone can write a provider, and more than 4,000 have been published.
- The workflow: write → plan → apply
The everyday Terraform workflow always has the same shape, whether you are changing one tag or creating an entire environment:
flowchart TD
W["1. WRITE<br/>edit the .tf files"] --> I["terraform init<br/>(only the first time, or when providers change)"]
I --> F["terraform fmt + validate<br/>formatting and syntax"]
F --> P["2. PLAN<br/>terraform plan"]
P --> R{"Is the plan<br/>what you expected?"}
R -- No --> W
R -- Yes --> A["3. APPLY<br/>terraform apply"]
A --> S[("Updated state")]
S --> W
Translated into EcoMarket's daily routine:
- Write: someone on the team opens a branch, edits
main.tfto add the product images bucket and opens a pull request. - Plan: CI runs
terraform planand posts the output on the PR. The team sees, literally, that one resource will be created and none destroyed. This is reviewed exactly as code is reviewed. - Apply: after approval and merge,
terraform applyexecutes the plan and updates the state.
The planning phase is what turns a risky operation ("I am about to touch production") into a reviewable one ("this is the exact diff I am about to run in production").
- Terraform compared with other tools
There is no single correct tool. This table places Terraform among its most common alternatives:
| Tool | Model | Scope | Language | State | Strength | Weakness |
|---|---|---|---|---|---|---|
| Terraform | Declarative | Cross-platform (4,000+ providers) | HCL | Its own state file | Huge ecosystem, explicit plan, one workflow for everything |
You have to manage state; HCL is not a general-purpose language |
| AWS CloudFormation | Declarative | AWS only | YAML/JSON | Managed by AWS (stacks) | No state to administer, native integration, drift detection | AWS only, verbose, slow deployments |
| Azure ARM / Bicep | Declarative | Azure only | JSON / Bicep DSL | Managed by Azure | Bicep is very readable, native integration | Azure only, less rich preview |
| Pulumi | Declarative with real languages | Cross-platform | TypeScript, Python, Go, C# | State file (its own or Pulumi Cloud) | Loops, tests and abstractions in a full language | Easier to write code that is hard to maintain; the team must know the language |
| Ansible | Idempotent procedural | System configuration (and some provisioning) | YAML | No persistent state | Excellent for configuring inside machines, agentless | Does not model dependencies or destroy what is left over; provisioning is its weakest area |
| Crossplane | Declarative | Cross-platform via Kubernetes | YAML (CRDs) | In Kubernetes etcd | Continuous, Kubernetes-style reconciliation | Requires a cluster and its learning curve |
The most frequent comparison is Terraform versus Ansible, and it is usually framed badly, because they do not compete at the same layer:
- Terraform creates the machine, the network, the load balancer and the database: provisioning.
- Ansible goes into the machine once it exists and installs packages, writes configuration files and starts services: configuration.
A very common combination in teams like EcoMarket's is Terraform for provisioning and Ansible (or cloud-init) for operating-system configuration; that split is covered in the lesson Configuring Servers.
- When Terraform is NOT the right tool
Presenting only the virtues would be dishonest. These are scenarios where Terraform is a poor choice:
- Ongoing internal server configuration. Installing packages and keeping configuration files up to date on 200 machines is a job for Ansible, Chef, Puppet or immutable images.
- High-frequency application deployments. If you deploy an application 30 times a day, use your platform's deployment tool (Argo CD, your PaaS CLI, a pipeline). Terraform is designed for infrastructure, whose rate of change is far lower.
- One-off imperative operations. Rotating a compromised key right now, taking a manual backup or restarting a service are actions, not desired states. Use the provider's CLI.
- Very short-lived ephemeral resources. Infrastructure that is born and dies within seconds at the application's discretion (temporary queues, per-request containers) does not fit a
plan/applycycle. - When the team cannot take on the cost of state. If nobody will be able to maintain a remote backend with locking, and the infrastructure is trivial, the web console may be good enough for a while. Being aware of the cost is part of the decision.
- Complex algorithmic logic. HCL is not a general-purpose language. If your configuration needs real algorithms, Pulumi or a generator that emits HCL may fit better.
- Real-world use cases
Where it clearly adds value:
- Multi-environment infrastructure. The EcoMarket case: the same code generates
dev,stagingandprodwith different parameters, eliminating drift. - Disaster recovery. Recreating an entire region becomes a
terraform applywith a different backend and different parameters. - Ephemeral test environments. Spinning up a complete environment for every pull request and destroying it on merge.
- Multi-cloud or hybrid strategies. A single workflow for AWS, Azure and your own data centre.
- SaaS service management. GitHub users, Datadog dashboards, Cloudflare DNS records, PagerDuty policies: everything has a provider.
- Security baselines. Defining policies, security groups and encryption in code, and using
planto detect any manual change. - Internal developer platforms. Exposing reviewed modules so that product teams can ask for a database without knowing the provider's details.
- HashiCorp, the BUSL licence and OpenTofu
A little context worth knowing before you choose a tool for a professional project.
HashiCorp is the company that created Terraform in 2014, alongside other well-known tools such as Vault (secrets management), Consul (service discovery), Nomad (orchestration) and Packer (image building). In 2024 it was acquired by IBM.
The licence change: up to version 1.5.5 (August 2023), Terraform was distributed under the MPL 2.0 licence, fully open source. From 1.5.6 onwards, HashiCorp switched to the BUSL 1.1 (Business Source License), which is a source-available licence, not an open-source one:
- You can read the code, modify it and use Terraform to manage your own infrastructure with no problem.
- What the licence forbids is offering a product that competes with HashiCorp's commercial offering based on that code.
- Each version reverts to MPL 2.0 four years after its release.
For 99% of teams — including EcoMarket's — this imposes no practical restriction: using Terraform internally is allowed. The change mainly affected companies building SaaS products around Terraform.
OpenTofu was born as a reaction to that change: it is a fork of Terraform 1.5.6 maintained under MPL 2.0 and donated to the Linux Foundation. Its characteristics:
| Aspect | Terraform | OpenTofu |
|---|---|---|
| Licence | BUSL 1.1 | MPL 2.0 (open source) |
| Governance | HashiCorp (IBM) | Linux Foundation |
| Binary | terraform |
tofu |
| Language | HCL | HCL (compatible) |
| Provider registry | registry.terraform.io | registry.opentofu.org (mirror + its own) |
| State | terraform.tfstate |
terraform.tfstate (same format) |
In practice, almost everything you learn in this course applies to both: the blocks, the init/plan/apply flow and the state format are compatible. The differences show up in exclusive features each project has added on its own (for example, the client-side state encryption OpenTofu introduced, or some Terraform Cloud/Stacks capabilities on the HashiCorp side).
In this course we use Terraform 1.5+ as our reference — it is what you will see in most job adverts and documentation — and we flag OpenTofu whenever it is relevant. Installing both is covered in the next lesson.
Common Mistakes and Tips
- Believing Terraform replaces everything. It is neither a configuration manager nor an application deployment orchestrator. Put it in its layer: provisioning.
- Thinking "multi-cloud" means "portable code". Terraform gives you a single workflow, but an
aws_instancedoes not turn into an Azure machine just by switching provider. Real portability demands your own abstractions and rarely pays off. - Underestimating state. It is the piece that makes the declarative model possible and also the main source of trouble. Spending time on module 3 is not optional.
- Mixing manual changes with Terraform. Once a resource is managed by Terraform, stop touching it in the console. If someone changes it by hand, the next
planwill try to revert it (this is called drift). - Starting with production. Learn with resources that cost nothing and carry no risk — as we will in this module with
localandrandom— and raise the stakes gradually. - Tip: always look at the
terraform planoutput before applying, even when you are certain. It is the cheapest safety net there is. - Tip: from day one, the infrastructure lives in Git. The value of IaC multiplies once you have history and reviews.
Exercises
Exercise 1: diagnosing manual infrastructure
Based on the EcoMarket situation described at the start, write a list of five concrete risks the company runs by having its infrastructure built by hand, and for each one state how infrastructure as code mitigates it. Do not copy the table: reason through the business impact of each risk.
Solution
(model answer; your wording may differ):
| Risk | Business impact | Mitigation with IaC |
|---|---|---|
prod cannot be recreated |
A regional outage could mean days of downtime and lost sales | The code is the rebuild recipe; it is applied in another region in minutes |
Drift between staging and prod |
Bugs that are not caught until production, with reputational cost | Both environments are generated from the same code; plan reveals any difference |
| Unaudited changes | Impossible to investigate incidents; regulatory compliance problems | Git gives you the author, date and reason for every change |
| Knowledge held by one person | Complete blockage if that person leaves or goes on holiday | The code is in the repository and the whole team can read it |
| No prior review | A faulty change goes straight into production | plan on a pull request plus mandatory approval |
Exercise 2: classifying tasks
For each of these EcoMarket team tasks, decide whether the right tool is Terraform, Ansible/cloud-init, the provider's CLI or an application deployment pipeline, and justify your answer in one sentence:
- Create the
stagingproduct images bucket. - Install and configure
nginxinside the application machines. - Deploy version 2.14.0 of
ecomarket-web(several times a day). - Urgently rotate an access key that has leaked into a log.
- Create a complete temporary environment for a three-day sales demo.
- Add a permanent firewall rule that lets the load balancer reach the application.
Solution
- Terraform: it is long-lived infrastructure, with a clear desired state, that must exist identically in all three environments.
- Ansible/cloud-init: it is configuration inside the operating system, not resource creation.
- Application deployment pipeline: high frequency and application artefacts; Terraform is not a continuous deployment tool.
- The provider's CLI: it is an urgent, imperative action, not a desired state. (Afterwards it is worth reflecting the new rotation policy in code.)
- Terraform: this is exactly its strong suit, and it also lets you destroy the whole environment when you are done with
terraform destroy. - Terraform: a permanent rule that forms part of the architecture and must be documented and versioned.
Exercise 3: declarative versus imperative
A colleague proposes solving EcoMarket's infrastructure management with a 600-line bash script that calls the provider's CLI. Write three technical arguments (not fashion or popularity ones) in favour of Terraform, and one honest scenario in which the script would be preferable.
Solution
(model answer):
Arguments in favour of Terraform:
- Automatic state management: the script would have to implement the "does this already exist?" logic by hand for every resource, and even then it would not know which resources it created in the past that should no longer exist.
- Dependency graph: Terraform works out the creation order and parallelises what it can; in the script the order is manual and fragile against any reordering.
- Change preview:
terraform planshows the exact effect before anything is touched. Reproducing that inbashwould mean, in practice, reimplementing Terraform.
A scenario where the script is preferable: a one-off, imperative operation on resources Terraform does not manage — for example, a nightly database dump into an archive bucket. There is no desired state to converge on there, only an action to execute.
Conclusion
In this lesson we have seen why Terraform exists before seeing how it is used. The points to take away:
- Infrastructure built by hand breeds drift, a lack of traceability and an inability to rebuild: exactly EcoMarket's problems.
- IaC turns infrastructure into versioned, reviewable and reproducible code.
- Terraform is a declarative, cross-platform tool with explicit state that computes and applies the difference between what you describe and what exists.
- Its architecture boils down to three pieces: core, providers and state.
- Its workflow is always write → plan → apply, and the planning phase is its greatest safety net.
- It is not good for everything: internal server configuration, frequent application deployments and one-off actions have better tools.
- Terraform has been distributed under BUSL 1.1 since version 1.5.6; OpenTofu is its open-source fork, practically compatible.
With the why clear, it is time to set up your working environment. In the next lesson, Installing Terraform, we will install the binary on Linux, macOS and Windows, verify its GPG signature, configure the editor and the plugin cache, and create the infra/ directory where the EcoMarket team will start writing its infrastructure as code.
