Terraform for developers: a complete beginner's guide

By

Tagged: Terraform

Learn what Terraform is, how infrastructure as code works, and how to create, change, inspect, and destroy infrastructure safely.

Terraform lets you define your infrastructure in plain text files and spin it up from the command line. Instead of opening a cloud dashboard and clicking through forms, you write down what you want in a file like this:

resource "docker_container" "web" {
  name  = "my-web-server"
  image = docker_image.nginx.image_id
}

Terraform reads that file, checks what’s already running, and shows you a plan of what it’s going to change. Once you review the plan and confirm it, Terraform talks to the right APIs and makes it happen.

This whole approach is called infrastructure as code. If you’ve never managed infrastructure before, Terraform can look intimidating at first because you immediately bump into providers, resources, state files, modules, and backends. You don’t need all of that on day one. In this guide, we’ll build a solid mental model, run a real example locally, and focus on the small slice of Terraform you need to get started.

What problem does Terraform solve?

Say you need a server for a new app. You open your cloud provider’s dashboard, spin up a virtual machine, pick a region, set up a network, add a firewall rule, and point a DNS record at it.

That works fine the first time. Then a few weeks later, you need a staging environment that matches production. Did you pick the exact same machine size? Did you copy that firewall rule over? Is the staging database configured the same way?

Now picture another developer joining the project. They open the dashboard and see the end result, with no history of why those choices were made or what changed along the way. Managing infrastructure by hand tends to break down in the same ways:

  • it’s hard to reproduce an environment from scratch
  • changes are hard to review before they go live
  • staging and production drift apart over time
  • nobody remembers every setting that was clicked months ago
  • rebuilding after an outage takes way longer than it should

Terraform moves all of those settings into text files you can keep in Git. You review infrastructure changes in a pull request just like application code, and you can reuse the same configuration whenever you need a fresh environment.

What is infrastructure as code?

Infrastructure as code means managing your setup through versioned files rather than clicking through web consoles. Those files can describe almost anything your stack relies on:

  • virtual machines
  • networks
  • databases
  • DNS records
  • storage buckets
  • load balancers
  • monitoring rules
  • GitHub repositories
  • services from many other platforms

Terraform isn’t just for servers. If a platform has an API and a Terraform provider, you can usually manage it from the same files.

Terraform turns infrastructure changes into code changes.

Because everything lives in Git, you can always see who changed a resource, why they changed it, and what the previous setup looked like.

Terraform is declarative

Terraform configuration is declarative, which means you describe the end state you want instead of spelling out every step to get there.

Suppose you want two application servers running. In an imperative script, you’d have to handle every case yourself:

  1. Check how many servers exist.
  2. If there are none, create two.
  3. If there is one, create another.
  4. If there are three, delete one.

With a declarative tool, you just state the target result:

instances = 2

Terraform figures out how to get from what’s currently running to what you asked for. It feels a lot like writing HTML or CSS, where you describe the result and let the browser handle the rendering steps. The big catch is that Terraform modifies real infrastructure that costs money and serves users, so reading the plan before applying anything matters a lot.

What can Terraform manage?

Terraform talks to external systems through plugins called providers. Each provider knows how to communicate with a specific API, and there are thousands of them in the Terraform Registry covering AWS, Microsoft Azure, Google Cloud, Cloudflare, Kubernetes, Docker, GitHub, and plenty of smaller services.

Every provider exposes its own resource types. The AWS provider gives you resources for EC2 instances, S3 buckets, and VPC networks, while the Cloudflare provider gives you resources for DNS records, zones, and Workers.

For our first example, we’ll use the Docker provider. That way you can practice the full Terraform workflow locally without creating a cloud account or spending any money.

What Terraform does not do

Terraform focuses on creating and managing infrastructure. It sits alongside your application code rather than replacing it, and it normally won’t build your app, run your test suite, or decide when a release should ship.

In a typical setup, each tool handles its own slice of the pipeline:

  1. GitHub Actions tests your application.
  2. Docker builds a container image.
  3. Terraform creates the network, server, and database.
  4. A deployment tool releases the new application version.

Teams draw these boundaries a bit differently depending on their stack. Even though Terraform can run shell commands, turning it into a general scripting or deployment tool usually makes the project harder to follow. My advice is to stick to Terraform for long-lived infrastructure resources.

How Terraform works

Before we run any commands, there are five moving parts worth knowing:

  1. Configuration describes what you want.
  2. Terraform Core reads the configuration and builds a plan.
  3. A provider talks to an external API.
  4. A resource represents one managed object.
  5. State connects your configuration to real objects.

Let’s walk through each one.

Configuration

Terraform automatically loads every .tf file in the current directory. Those files are written in HashiCorp Configuration Language, or HCL, which is designed to stay readable as configs grow:

resource "docker_image" "nginx" {
  name = "nginx:stable-alpine"
}

This block declares a single resource. docker_image is the resource type coming from the Docker provider, nginx is the local name we picked so other resources can reference it, and name tells the provider which image to pull.

Terraform Core

Terraform Core is the main binary you run from your terminal. It reads your .tf files, figures out dependencies between resources, checks the saved state, asks providers what currently exists, and computes a plan.

When a container depends on an image, Terraform works out that the image has to be ready first. You don’t have to manually specify the order.

Providers

Providers are standalone plugins that Terraform downloads when you run terraform init. Each provider handles the details of its remote system, so Terraform Core doesn’t need built-in knowledge of AWS, Docker, or any other platform. That plugin split is what lets Terraform support so many services with one workflow.

Resources

A resource is a single object that Terraform manages, like a server, bucket, database, container, or DNS record. Inside Terraform, every resource has a unique address. Take this block:

resource "docker_image" "nginx" {
  name = "nginx:stable-alpine"
}

Its address is:

docker_image.nginx

You’ll see these addresses everywhere in Terraform’s output, including plans, state commands, and error messages.

State

Terraform needs to keep track of which real-world object corresponds to each resource in your .tf files, and it stores that mapping in state. In a local project, state lives in a file called terraform.tfstate.

Think of state as Terraform’s memory. Your configuration might define docker_container.web, while the state file records the exact container ID Docker gave it. The next time you run Terraform, it compares three things:

  • your configuration
  • its saved state
  • the real infrastructure

State is a huge part of working with Terraform safely, so we’ll come back to it in more detail later.

Fig 1 · 1/6Plan apply
configuration · state and container not created yet

The core Terraform workflow

The official Terraform workflow boils down to three main stages:

  1. Write
  2. Plan
  3. Apply

In day-to-day work, you’ll usually run a couple of extra helper commands along the way:

terraform init
terraform fmt
terraform validate
terraform plan
terraform apply

Here’s what each command does:

  • init prepares the directory and downloads providers
  • fmt formats your .tf files
  • validate checks the configuration
  • plan previews changes
  • apply performs the changes

There’s one more command you should know right from the start, because it deletes everything managed by the current configuration:

terraform destroy

Use that command carefully, especially once your config points at live cloud infrastructure.

Install Terraform

Follow the official Terraform installation guide for your operating system. Once the install finishes, verify that the CLI is available:

terraform version

You’ll also need Docker for the hands-on example in this guide. If you’re new to Docker, check out my introduction to Docker first, then install Docker Desktop. Before creating the project, make sure the Docker daemon is running:

docker version

With both tools ready, we can set up our first Terraform project.

Create your first Terraform project

Start by creating a new directory for the project:

mkdir terraform-docker-demo
cd terraform-docker-demo

Inside it, create a file named main.tf and add this configuration:

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.2"
    }
  }
}

provider "docker" {}

resource "docker_image" "nginx" {
  name         = "nginx:stable-alpine"
  keep_locally = false
}

resource "docker_container" "web" {
  name  = "terraform-web"
  image = docker_image.nginx.image_id

  ports {
    internal = 80
    external = 8080
  }
}

This follows the same structure as HashiCorp’s official Docker tutorial. Let’s walk through each block before we run it.

The terraform block

The first block configures Terraform itself and lists the providers this project depends on:

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.2"
    }
  }
}

Here we’re telling Terraform to pull the Docker provider from kreuzwerker/docker, accepting compatible releases in the 4.x series starting from 4.2. Locking down provider versions matters because providers can change resource arguments or behavior between releases, and a version constraint keeps your setup predictable.

The provider block

Next comes the configuration block for the Docker provider:

provider "docker" {}

Leaving it empty tells the provider to use its default connection settings, which on macOS and Linux connect straight to your local Docker daemon. Cloud providers need more setup here, like a region, account details, or credentials. Keep long-lived secrets out of your committed .tf files, and pass credentials through environment variables or workload identity systems instead.

The image resource

This resource makes sure the Nginx image is available locally:

resource "docker_image" "nginx" {
  name         = "nginx:stable-alpine"
  keep_locally = false
}

We gave this resource the local name nginx. That’s only the identifier Terraform uses inside the configuration, separate from the Docker image name itself.

The container resource

The next resource creates and runs the container:

resource "docker_container" "web" {
  name  = "terraform-web"
  image = docker_image.nginx.image_id

  ports {
    internal = 80
    external = 8080
  }
}

Look closely at this line inside the block:

image = docker_image.nginx.image_id

Because the container references the image resource, Terraform detects the dependency automatically and prepares the image before starting the container. The port block maps port 8080 on your computer to port 80 inside the container.

Initialize the directory

Now initialize the project directory from your terminal:

terraform init

Terraform downloads the Docker provider into a hidden .terraform folder and generates a .terraform.lock.hcl file. Commit .terraform.lock.hcl to Git so everyone gets the exact same provider version, and leave .terraform out of Git since Terraform can recreate it anytime.

You’ll run terraform init whenever you first clone a Terraform repo, and again whenever you change provider or module requirements.

Format the configuration

Next, format your .tf files with:

terraform fmt

Terraform rewrites every configuration file in the directory to match its standard style, which keeps code reviews focused on real changes instead of indentation. I run terraform fmt before every commit.

Validate the configuration

Before previewing any changes, check that the configuration is valid:

terraform validate

Terraform checks your syntax and verifies that internal references match up. When everything is in order, you’ll get output like this:

Success! The configuration is valid.

This runs locally to catch typos and broken references early, before Terraform talks to any API. Live issues like missing cloud permissions or rejected API calls only show up later when you plan or apply.

Preview the changes

Start by running a plan to see what Terraform wants to do:

terraform plan

Terraform reads your configuration, checks what’s currently running, and prints an execution plan. You should see a summary line near the bottom like this:

Plan: 2 to add, 0 to change, 0 to destroy.

That tells you Terraform is going to create the image and the container. The plan uses diff-style symbols so you can scan what’s about to happen:

  • + creates a resource
  • ~ updates an existing resource in place
  • - destroys a resource
  • -/+ replaces a resource (destroys the old one and creates a new one)

Watch out for -/+ whenever you read a plan. Some properties can’t be modified on a live resource, so Terraform has to tear the old one down and build a new one from scratch. For a local Docker container that’s completely harmless, while for a production database it can mean downtime or lost data. Always read the list of resources Terraform plans to touch instead of just glancing at the summary numbers at the bottom.

Apply the configuration

Now run apply so Terraform creates those resources:

terraform apply

Terraform calculates the plan again and pauses to ask for confirmation. Confirm the prompt with:

yes

Terraform pulls the Docker image and spins up the container. Once it finishes, open http://localhost:8080 in your browser and you’ll see the Nginx welcome page. You wrote a short text file describing a web server, and Terraform built it for you.

Inspect what Terraform manages

You can ask Terraform to list every resource it’s tracking right now:

terraform state list

That prints the resource addresses stored in your state file:

docker_container.web
docker_image.nginx

If you want to look closer at a single resource, you can inspect it directly:

terraform state show docker_container.web

Terraform prints out all the attributes it knows about that container. You can also print the entire current state in a readable format with:

terraform show

These commands are handy when you’re learning or debugging. Use them to read state, and avoid editing the state file by hand.

Change the infrastructure

Creating resources once is nice, but infrastructure as code really pays off when you need to change something. Open main.tf and update the external port:

ports {
  internal = 80
  external = 9090
}

Run another plan to see how Terraform handles the update:

terraform plan

Take a look at the output. Because the container’s port mapping changed, the Docker provider may need to replace the container rather than updating it in place. Apply the change to put the new port live:

terraform apply

Once you approve it, open http://localhost:9090 in your browser. The old port setup is gone, the new container is serving traffic on port 9090, and your main.tf file and Git history both show the exact change you made.

What happens if you run apply again?

Try running apply a second time without editing anything:

terraform apply

Since nothing changed, Terraform reports that your infrastructure already matches the configuration:

No changes. Your infrastructure matches the configuration.

Running the same configuration over and over doesn’t spin up duplicate resources. Terraform compares your files against its state and the provider’s current data, sees that everything you asked for already exists, and leaves it alone.

What is infrastructure drift?

Drift happens when your live infrastructure no longer matches what’s written in your Terraform files. For example, someone might stop or modify the container by hand:

docker stop terraform-web

Now your configuration says the container should be running, while the real environment disagrees. Run a plan to see how Terraform reacts:

terraform plan

Terraform inspects the container and plans whatever actions are needed to bring it back in line with your files. Cloud dashboards make quick manual edits tempting, so once Terraform manages a resource, make your changes in the configuration files instead. Otherwise, the next Terraform run can quietly undo whatever you changed by hand.

Destroy the example

When you’re done experimenting, tear down the resources you created:

terraform destroy

Terraform prints a destruction plan and waits for confirmation. Read through what it’s about to remove, then type yes to delete both the container and the image. Getting into the habit of destroying test setups now will save you from surprise bills once you start provisioning paid cloud resources.

Add an input variable

Hard-coded values work fine for a first test, but reusable configurations need inputs. Create a file named variables.tf to define a variable:

variable "external_port" {
  description = "Port used to access Nginx from the host"
  type        = number
  default     = 8080
}

Next, reference that variable inside main.tf:

ports {
  internal = 80
  external = var.external_port
}

Run Terraform with no extra flags and it’ll pick up the default value:

terraform plan

When you want a different value, you can pass it right from the command line:

terraform plan -var="external_port=9090"

Using variables lets you reuse the same configuration across setups without copy-pasting blocks. Terraform supports strings, numbers, booleans, lists, maps, objects, and more, though it’s best to stick with simple types until a configuration genuinely needs structured inputs.

Add an output

An output prints useful values after an apply so you don’t have to dig through state to find them. Create outputs.tf with your output definition:

output "web_url" {
  description = "URL of the local Nginx server"
  value       = "http://localhost:${var.external_port}"
}

Apply the configuration and Terraform will print the output at the end of the run:

terraform apply

Whenever you want to look that value up again later, run:

terraform output web_url

Outputs also help connect separate configurations. For instance, a networking setup might export a subnet ID so an application setup can plug right into it.

How Terraform uses files

Terraform reads every .tf file in your current directory together as a single configuration. You’ll commonly see layouts like this:

main.tf
variables.tf
outputs.tf
versions.tf

Those filenames are just community conventions, so Terraform doesn’t treat variables.tf or outputs.tf any differently than main.tf. You could put everything in one file and it would work the same way. Splitting files helps people navigate a larger project, while a five-line example is much easier to read in a single file.

What should go into Git?

When you put a Terraform project in Git, commit these files:

  • .tf configuration files
  • .terraform.lock.hcl
  • documentation like README.md

Keep these out of version control:

  • the .terraform directory
  • local state files
  • saved plan files
  • files holding secret variable values

Here’s a minimal .gitignore you can start with:

.terraform/
*.tfstate
*.tfstate.*
*.tfplan
*.tfvars

Not every .tfvars file contains secrets, though plenty of them do, so check what’s inside before committing one. On the flip side, you do want to commit .terraform.lock.hcl so everyone on the team and every CI job pulls the exact same provider versions.

Why state needs special care

Your state file can hold resource IDs, addresses, output values, and sensitive data returned by providers, so never commit terraform.tfstate to a shared Git repository.

Once you’re working with a team, move state into a remote backend built for shared access, like HCP Terraform or a supported cloud storage backend. A remote backend solves two problems right away:

  • everyone reads from the same up-to-date state
  • state locking stops two apply runs from colliding at the same time

If two teammates modify the same infrastructure from separate local state files, Terraform ends up making bad decisions based on stale data. Local state works fine for a tutorial like this one, while shared production infrastructure belongs in remote state. That’s all you need to know about state to get moving, and you can leave advanced state surgery commands for much later.

What is a Terraform module?

A module is a group of Terraform resources packaged to be used together. You’re already working inside one: the directory where you run Terraform is called the root module.

Beyond the root module, you can call reusable modules whenever you want to bundle a common setup. For example, a team might build a module that always sets up:

  • a virtual network
  • two private subnets
  • standard security rules
  • logging settings

Then an application team can call that module instead of copying all those resource blocks by hand. Think of modules like functions or packages in regular code: they take inputs, build a related set of resources, and expose outputs. Just don’t wrap every single resource in a module from day one. Start with plain resources and extract a module once you spot a real boundary or a pattern you keep repeating.

How a team uses Terraform

Most teams settle on a workflow that looks something like this:

  1. A developer edits the Terraform configuration.
  2. They run terraform fmt and terraform validate.
  3. Automation runs terraform plan on the pull request.
  4. Teammates review both the code diff and the plan output.
  5. Once the pull request is approved, trusted automation runs terraform apply.

Treat the plan output as a first-class part of code review. A one-line edit in a .tf file can easily trigger a replacement on a critical resource, so you need the diff to see what changed and the plan to see what Terraform is going to do about it. It also pays to keep production applies off individual laptops and inside a controlled runner, which gives you a clean audit trail and avoids subtle differences between local setups.

Terraform and environment variables

Providers commonly pick up credentials from environment variables, which lets you pass an API token without writing it into main.tf. That’s much safer than hard-coding secrets, though environment variables still need careful handling: keep them out of logs and shell history, and store them in your CI platform’s encrypted secrets when running automation.

Also remember that marking a Terraform variable as sensitive hides it in some terminal output, while the underlying value can still end up stored in your state file. Handle your Terraform state with the same care you give to secrets.

Terraform versus a shell script

A shell script gives the machine a sequence of commands to run, while Terraform describes the resources you want and keeps track of their identities. You can write a shell script to create a server, sure, and then you’re on the hook for handling every edge case yourself:

  • the server already exists
  • a single setting changes
  • someone deleted the resource by hand
  • several resources depend on each other
  • you need to tear everything down cleanly

Terraform already has a built-in model for all of those situations. Shell scripts are still useful for plenty of tasks, while Terraform is built specifically for managing resource lifecycles.

Terraform versus Docker

Docker packages and runs applications inside containers, while Terraform creates and configures infrastructure resources. In the example above, Terraform talked to Docker’s API to pull an image and launch a container: Docker handled running the container, and Terraform described and tracked it. They solve two different layers of the stack and work well side by side.

Terraform versus Kubernetes

Kubernetes runs and coordinates containerized workloads across a cluster. Terraform fits naturally around it, provisioning the cluster itself along with networks, service accounts, and the rest of the surrounding infrastructure, while Kubernetes runs the applications inside.

Terraform does have a Kubernetes provider, though you don’t have to manage every Kubernetes object with it. Many teams stick to Terraform for the cluster and cloud resources, and use Kubernetes manifests or Helm for deploying applications so it’s always obvious which tool owns what.

Terraform versus cloud-specific tools

Tools like AWS CloudFormation and Azure Bicep are built specifically for one cloud provider, whereas Terraform gives you a single workflow across many platforms. Neither option wins in every situation. A native cloud tool often supports brand-new platform features sooner, while Terraform pays off when your stack spans multiple services or when your team wants one tool they already know. Pick whichever fits your team and project best instead of forcing one choice everywhere.

Common beginner mistakes

Applying without reading the plan

Don’t treat terraform apply like a dialog box you click through on autopilot. Always read which resources are going to be created, modified, replaced, or destroyed before you type yes.

Editing generated state

Stick to editing your .tf files and running Terraform commands instead of opening the state file by hand. Editing state manually is a last-resort recovery move, and doing it casually is an easy way to break Terraform’s tracking.

Committing secrets

Keep API keys, tokens, and passwords out of any Terraform files you commit to Git. And keep in mind that sensitive values can still land in your state file, so protect state access too.

Making manual dashboard changes

Tweaking a Terraform-managed resource in a cloud console introduces drift, and the next apply can overwrite your changes. If Terraform owns the resource, update it in your Terraform configuration instead.

Using one state for everything

Stuffing an entire company’s infrastructure into a single state file gives every run a huge blast radius. You don’t need an elaborate multi-state layout on day one. Just avoid letting unrelated systems pile up forever inside one configuration.

Copying a large module without understanding it

Public modules can save a lot of typing, and they can also spin up dozens of resources you didn’t expect. Check a module’s inputs, outputs, underlying resources, and version requirements before pulling it into your project.

Assuming a successful plan guarantees a successful apply

A plan only reflects what Terraform sees at the moment it runs. An apply can still fail if your credentials lack a permission, a cloud API errors out, or another process changes something before your run starts, so always check the apply output too.

A small Terraform command reference

Here are the commands you’ll reach for most during your first week with Terraform.

Initialize a project:

terraform init

Format your .tf files:

terraform fmt

Validate the configuration:

terraform validate

Preview planned changes:

terraform plan

Apply those changes:

terraform apply

List every tracked resource:

terraform state list

Print your outputs:

terraform output

Destroy all managed resources:

terraform destroy

When should you use Terraform?

Terraform works best when you need infrastructure that’s repeatable, reviewable, and maintained over time. It’s a good fit when:

  • your project has several related infrastructure resources
  • you need staging and production environments
  • multiple people manage the same infrastructure
  • you want changes reviewed in Git
  • rebuilding manually would be slow or risky

You probably don’t need it for a tiny experiment with one disposable resource, though. Setting it up takes effort, and you’ll have to maintain both the configuration and the state over time.

The Terraform loop

Whenever Terraform starts to feel confusing, come back to this loop:

  1. Your configuration says what you want.
  2. State remembers what Terraform is managing.
  3. Providers read and change the real systems.
  4. Plan shows the difference before anything changes.
  5. Apply runs the actions you approved.

You can leave modules, remote backends, workspaces, import operations, policy systems, and CI automation for later. Start by getting comfortable reading a small configuration and its plan, then create something, change it, and destroy it. Going through that loop yourself will teach you more than memorizing every Terraform term.

Want me to talk about your product? You can sponsor this site.