, , ,

Infrastructure as Code: Build Servers From Files, Not Clicks (DevOps for Beginners, Part 10)

Infrastructure as Code explained with Terraform: describe servers in files, use the plan and apply loop, understand the state file, and avoid drift and lock conflicts.

12 min read
Before you start
To try the hands-on steps you will need Terraform or OpenTofu installed, and Docker for the example. Everything here is free.
12 min read
Before you start
To try the hands-on steps you will need Terraform or OpenTofu installed, and Docker for the example. Everything here is free.
DevOps for Beginners · Part 10 of 18
The idea
Infrastructure as Code means you describe your servers, networks, and databases in text files instead of clicking around a cloud console. A tool like Terraform reads those files and builds the real thing, and rebuilds it identically any time. Your infrastructure becomes reviewable, versioned in Git, and repeatable. The days of nobody remembers how that server was set up are over.

For the college passout or career switcher who has clicked through a cloud console once or twice and sensed there had to be a saner way to manage servers than remembering which buttons you pressed.

Someone set up a server eight months ago by clicking through a web console. They picked a size, a region, some firewall rules, a disk, and a dozen other settings, and none of it was written down. Today that server dies, and the person who built it has left the company. Now the team is reverse-engineering a machine nobody documented, under pressure, while the site is down. This exact story plays out constantly, and Infrastructure as Code is the industry is answer to it.

The whole approach begins with a file. Here is a small Terraform configuration that describes one container running nginx, using the concepts you already know from Part 8. Read it as a description of what should exist, not a script of steps.

terraform {
  required_providers {
    docker = {
      source = "kreuzwerker/docker"
    }
  }
}

resource "docker_container" "web" {
  name  = "web"
  image = "nginx:latest"
  ports {
    internal = 80
    external = 8080
  }
}

The provider block says which platform to talk to. The resource block declares one container named web, from the nginx image, with a port published. It describes a desired result, and Terraform figures out how to reach it.

Part 9 showed Kubernetes keeping containers in a desired state. Terraform brings that same declarative idea one layer down, to the servers and networks the containers run on. You declare what should exist, and the tool makes reality match. That shared idea, declare the goal and let the tool reconcile, runs through all of modern infrastructure.

Clicking versus declaring

Managing infrastructure by clicking through a console is sometimes called ClickOps, and it works right up until it does not. The problem is not that clicking is hard. It is that a click leaves no record, cannot be reviewed by a teammate, and cannot be repeated exactly. If you need the same setup in a second region, or a fresh copy for testing, you are clicking through the whole thing again and hoping you match it. Infrastructure as Code fixes every one of those weaknesses at once.

QuestionClicking in a consoleInfrastructure as Code
Is it written down?No, only in memoryYes, in a file
Can a teammate review it?Not reallyYes, in a pull request
Can you rebuild it exactly?Only by hand, error proneYes, one command
Is there a history?NoYes, in Git

The core loop: write, plan, apply

Terraform has a simple, safe rhythm. You write the configuration, initialize once to download the provider, preview the change with plan, then make it real with apply. The plan step is what makes Terraform feel safe: it shows you exactly what it will do before it touches anything, so there are no surprises.

$ terraform init
Terraform has been successfully initialized!
$ terraform plan
  + resource "docker_container" "web" {
      + name  = "web"
      + image = "nginx:latest"
    }
Plan: 1 to add, 0 to change, 0 to destroy.
$ terraform apply
docker_container.web: Creation complete after 2s
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Read the plan line: 1 to add. That green plus is Terraform promising to create one thing and change nothing else. Run apply and it happens. The real proof of the declarative model comes when you run apply a second time without changing the file.

$ terraform apply
No changes. Your infrastructure matches the configuration.

Nothing happens, because reality already matches your file. That property is called idempotence, and it is what lets you run Terraform a hundred times safely. It only ever does the work needed to close the gap between your file and the world.

write .tfplanapplystate updatedPlan previews, apply changes reality, state records what now exists.
CommandWhat it does
terraform initDownload providers, set up the folder
terraform planPreview what will change, touch nothing
terraform applyMake reality match the files
terraform destroyTear down everything it created

The state file is the heart of it

To know what to add, change, or leave alone, Terraform keeps a record of everything it has built, called the state. This file is how Terraform maps your configuration to the real resources it created. When you run plan, it compares three things: your files, the state, and the real world. Understanding state is the difference between using Terraform and fighting it.

Two rules save beginners a world of pain. First, never edit the state file by hand, because a wrong edit can make Terraform lose track of real resources or try to recreate things that already exist. Second, on any team, store the state remotely in a shared, locked location rather than on one laptop. If two people keep their own local copies, their views of reality drift apart and the next apply does something nobody intended.

Worked example: two people apply at once
You run apply and Terraform stops with this:

Error: Error acquiring the state lock
Lock Info:
Who: priya@laptop

This is a good error, not a scary one. With remote state, Terraform locks it while one person applies so that two people cannot change the same infrastructure at the same moment and corrupt the record. The message is telling you a teammate is mid-apply. The fix is simply to wait until their run finishes and the lock releases, then run yours. Teams that skip remote state never get this protection, and instead get the far worse problem of two conflicting applies quietly clobbering each other.

Drift: when someone clicks in the console anyway

The most common way Infrastructure as Code goes wrong is drift. You manage a server with Terraform, then someone opens the console and changes a setting by hand to fix something quickly. Now the real world no longer matches your files. The next time anyone runs plan, Terraform notices the difference and wants to undo that manual change to get back to what the files say. If the manual change was important and undocumented, that surprise apply can break things.

your files saysize mediumreality is nowsize largesomeone clickedThe gap is drift. The fix is to change the file, not the console.

The discipline that prevents drift is simple to state and hard to keep: once a resource is managed by Terraform, you change it only by editing the files and running apply, never by clicking. The console becomes read-only for anything under Terraform’s control. Teams that hold this line get infrastructure they can trust and rebuild. Teams that do not slowly return to the same mystery-server problem Infrastructure as Code was supposed to solve.

Write it once, reuse it everywhere

Most teams need the same shape of infrastructure more than once: a development environment, a staging environment, and production, all similar but not identical. Copying the whole configuration three times and editing each copy is how mistakes creep in. Terraform solves this with two features. Variables let you pull the values that change, a name, a size, a region, out of the configuration and pass them in, so one file serves many uses. Modules go further and package a whole set of resources into a reusable block you call like a function, feeding it different variables each time.

one moduleweb server setupdevstagingproductionSame module, different variables, three matching environments.

The payoff is real. Your staging environment becomes a true rehearsal for production because both are built from the same module, so a change tested in staging behaves the same when you promote it. You do not need modules on your first day, and writing a plain configuration first is the right way to learn. But knowing they exist tells you why teams do not copy and paste infrastructure: they factor the common parts into a module and vary only what must differ. That is the same instinct that makes good code, applied to servers.

Terraform or OpenTofu: which to learn

You will hear both names, so here is the honest picture. Terraform is made by HashiCorp, which IBM acquired, and its recent releases ship under the Business Source License rather than a fully open one. OpenTofu is a community fork under the Linux Foundation that stays open source, and its commands and files are nearly identical. For a beginner in 2026, this is not a decision to agonize over. The concepts and syntax you learn transfer between them almost completely, so learn the ideas on whichever your future team uses.

My actual advice: do not let the license debate slow you down. Write a few configurations, run plan and apply, break something and fix it, and you will carry that skill to either tool. Interviewers do like to hear that you know why the split exists, so keep the one line answer ready: OpenTofu forked to stay open source after Terraform’s license changed. Beyond that, spend your energy on the workflow, not the logo.

Interview question you will meet
What is the Terraform state file and why does it matter? Answer: state is Terraform’s record of the real resources it manages, and it is how plan knows the difference between your files and reality. Add the two things that show real experience: you never edit state by hand, and on a team you keep it in remote, locked storage so concurrent applies cannot corrupt it. That answer tells an interviewer you have actually run Terraform with other people, not just followed a solo tutorial.
Why this matters on day one
On a team that uses Infrastructure as Code, you will not click in the console to make changes. You will edit a file, open a pull request, and let a reviewer see the plan output before anything happens. Being comfortable reading a plan, knowing that add means create and destroy means delete, and never running apply on red or unclear output, makes you safe to hand infrastructure to. The junior who says the plan wants to destroy the database, that cannot be right, let me check has just prevented an outage, and that instinct is what teams value most.
Try it yourself
Free, about thirty minutes, no cloud account needed if you have Docker from Part 8. Install Terraform or OpenTofu, save the Docker configuration from the top of this part, and run terraform init, then plan, then apply. Open localhost:8080 to see nginx running. Now run apply again and watch it report no changes. Finally run terraform destroy and watch the container disappear. How to check you did it right: plan shows 1 to add the first time and no changes the second, and destroy removes exactly what you created.
In practice
Read the summary line of every plan before you approve it, and read it out loud if you have to. Plan: 2 to add, 1 to change, 0 to destroy is calm. The moment you see a destroy count you did not expect, stop. A change that quietly replaces a database or wipes a disk shows up right there in the plan, and the plan is the last safe place to catch it. Experienced engineers treat an unexpected destroy in a plan the way a pilot treats a warning light: you do not proceed until you understand it.

Terraform questions that come up on the job

Is Terraform only for the cloud?
No. It talks to hundreds of platforms through providers: cloud services, Docker, Kubernetes, DNS, even some software as a service tools. Anything with a provider can be managed as code. The cloud is the most common use, but the model is general.

How is Terraform different from Ansible?
Terraform is best at creating and managing infrastructure, the servers and networks themselves. Ansible, coming up in Part 11, is best at configuring what runs inside those servers. Many teams use Terraform to build the machines and Ansible to set them up, and the two fit together.

What happens if I lose the state file?
Terraform loses its map of what it built, and it may try to recreate resources that already exist. This is exactly why teams store state remotely with backups and locking. Losing local state is a recoverable but painful mess, and it is the strongest argument for remote state from day one.

Should I run apply straight from my laptop?
For learning, yes. For real production, no. Mature teams run Terraform through a pipeline, the same CI/CD idea from Part 7, so every change is reviewed and applied consistently rather than from someone is personal machine. Start local to learn, then graduate to a pipeline.

You can now describe infrastructure as files instead of clicks, which is one of the biggest force multipliers in the field. Next up is Part 11 on Ansible, the tool that configures what runs inside the servers you just learned to create.

New here? Start with Part 9 on Kubernetes and Part 3 on the toolchain map. The Cloud for Beginners series pairs well for the resources Terraform creates.

DevOps for Beginners · Part 10 of 18
« Previous: Part 9  |  Complete Guide  |  Next: Part 11

References

Terraform documentation
OpenTofu documentation
Terraform: State

About The Author


Discover more from Journal of Intelligent Infrastructure – By Dr Pranay Jha

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Architect’s Toolkit

About the Author

Dr. Pranay Jha is a Cloud and AI Consultant with 18+ years of experience in hybrid cloud, virtualization, and enterprise infrastructure transformation. He specializes in VMware technologies, multi-cloud strategy, and Generative AI solutions. He holds a PhD in Computer Applications with research focused on Cloud and AI, has published multiple research papers, and has been a VMware vExpert since 2016 and a VMUG Community Leader.

Discover more from Journal of Intelligent Infrastructure - By Dr Pranay Jha

Subscribe now to keep reading and get access to the full archive.

Continue reading