Introduction to Infrastructure as Code (IaC) & Terraform Basics
6 min read
Module 1: Introduction to Infrastructure as Code (IaC) & Terraform Basics
Welcome to the Terraform course! 🚀 Grab a coffee (or a calming herbal tea if you've recently deleted a production database), and let's dive into the world of Infrastructure as Code.
We are going to move from "clicking around in a web console hoping you remember what you did" to "God-mode infrastructure management."
1. The "Why" Before the "How": What is IaC and Why Terraform?
The Problem: The Era of "ClickOps"
Imagine you are building a house. But instead of blueprints, you just shout instructions at the builders as you go. "Put a wall there! No, wait, move it two feet left. Actually, delete that room."
In the IT world, we call this ClickOps. You log into AWS/Azure/GCP, click "Create Instance," manually select the RAM, manually set the firewall rules, and hit launch.
Why is this bad?
- It's not repeatable: If you need to build the exact same environment for "Staging," you have to remember every single click.
- Human Error: You will forget to tick that one security box, and suddenly your database is mining crypto for a stranger in a basement.
- No History: If the server crashes, you have no record of how it was configured.
The Solution: Infrastructure as Code (IaC)
Definition: Infrastructure as Code (IaC) is the management and provisioning of infrastructure through code instead of manual processes.
With IaC, you write a configuration file (the blueprint). You give that file to a tool, and the tool builds the house exactly as described. If the house burns down? You just run the file again.
Why Terraform?
There are many IaC tools (Ansible, Pulumi, CloudFormation), but Terraform is the industry heavyweight champion.
- Vendor Agnostic: It works with AWS, Azure, Google, Kubernetes, Datadog, Spotify playlists (yes, really), and Domino's Pizza (also really). You learn one syntax to rule them all.
- Declarative: You tell Terraform what you want (e.g., "I want 3 servers"), not how to do it. Terraform figures out the steps.
- State Management: Terraform remembers what it built. If you change your code to ask for 5 servers, it knows it already created 3, so it only adds 2.
Fun Fact: The Domino's Pizza provider for Terraform is real. You can literally
terraform applya pepperoni pizza to your front door. This is the peak of human engineering. 🍕
2. Setting up the Terraform Environment
We need two things: The Terraform CLI (Command Line Interface) and a code editor that understands it.
Step A: Install the Terraform CLI
Terraform is a single binary. It's lightweight and doesn't run in the background. It only runs when you tell it to.
Note: Always verify you are installing the official HashiCorp release, not a verified wrapper.
🍎 macOS (Homebrew)
Don't use the default brew install terraform immediately; verify the tap to ensure you get the HashiCorp official version.
brew tap hashicorp/tap
brew install hashicorp/tap/terraform🪟 Windows (Chocolatey)
Run your PowerShell as Administrator:
choco install terraform🐧 Linux (Ubuntu/Debian)
Do not just apt-get install terraform directly without the gpg key, or you might get an ancient version.
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraformVerify installation:
Type this in your terminal. If you see a version number, you win.
terraform -versionStep B: Editor Configuration
We are using VS Code (Visual Studio Code). It is the industry standard for Terraform.
- Open VS Code.
- Go to the Extensions Marketplace (Block icon on the left).
- Search for "HashiCorp Terraform".
- Install the official extension by HashiCorp.
Why? This gives you syntax highlighting and autocompletion. Without it, writing Terraform feels like writing code in Notepad—painful and dangerous.
3. Your First Configuration: "Hello World" in Terraform
The Concept: Providers and Resources
In Terraform, everything follows a hierarchy:
- Provider: The plugin that talks to the API (e.g., AWS, Azure, or your local filesystem).
- Resource: The specific object you want to create (e.g., a Server, a Bucket, or a File).
The Task
We will not start with AWS because configuring API keys takes time. We will start with the local provider. We will tell Terraform to create a text file on your computer.
The Code
Create a folder named terraform-demo. Inside, create a file named main.tf.
Copy and paste this:
resource "local_file" "pet" {
filename = "${path.module}/pets.txt"
content = "We love infrastructure!"
}Explanation (The Anatomy of a Block)
resource: Keyword telling Terraform we are defining an object."local_file": The Type. This determines what properties are available (defined by the provider)."pet": The Name. This is an internal variable name for Terraform. You can call itpizza,server, orbob. It does not affect the actual filename created.filename: An Argument. Where should the file go?content: An Argument. What should be inside?
4. The Core Workflow: init, plan, apply, destroy
This is the ritual. You will perform these four steps thousands of times in your career. Memorize them.
Step 1: terraform init (Initialize)
Problem: You wrote local_file, but Terraform doesn't know how to create files yet. It needs the code (plugin) for the local provider.
Action: Run this in your terminal inside the folder.
terraform initWhat happened?
Terraform looked at your code, saw you need local_file, went to the internet, downloaded the "Local" provider plugin, and saved it in a hidden .terraform folder.
Step 2: terraform plan (The Dry Run)
Problem: You don't want to run code without knowing what it will do. What if it deletes your boss's laptop?
Action:
terraform planWhat happened?
Terraform compares your code against the current state of the world. It will output a plan with + signs (create), - signs (destroy), or ~ signs (modify).
- Green
+means it will create the filepets.txt. - Industry Standard: Always read the plan. Never skip this. This is your safety net.
Step 3: terraform apply (The Execution)
Problem: The plan looked good. Now we want the actual file.
Action:
terraform applyTerraform will show the plan again and ask for confirmation. Type yes.
What happened?
- The file
pets.txtwas created in your folder. Go check it! - Terraform created a file called
terraform.tfstate.
Under the Hood (Important!): The
terraform.tfstatefile is Terraform's memory. It maps your code (resource "local_file" "pet") to the real world (the actual file on disk). Never edit this file manually. If you do, you break reality.
Step 4: terraform destroy (The Cleanup)
Problem: We are done with this file. We want to clean up.
Action:
terraform destroyType yes to confirm.
What happened?
Terraform looked at its state file, found the file it created, and deleted it.
🎯 Summary
- IaC solves the problem of manual, error-prone "ClickOps."
- Terraform is a declarative tool: you say what you want, it figures out how.
- Workflow:
init: Get the tools.plan: Check the blueprint.apply: Build the house.destroy: Demolish the house.
You have just successfully practiced the lifecycle of infrastructure code. Next, we will take this logic and apply it to the Cloud.
📚 References & Docs
Challenge
Challenge
Your task is to write a complete Terraform configuration file (main.tf). This configuration will use the local provider to manage two files on a local filesystem, creating a dependency between them.
Requirements:
- Terraform Block: Declare that the configuration requires the
localprovider from thehashicorp/localsource, version~> 2.1. - First Resource (Inventory):
- Define a resource of type
local_file. - Name it
server_inventory. - Set its
filenameattribute to"inventory.txt". - Set its
contentto the following multi-line string:nginx# Server List web_server_01 db_server_01 app_server_01
- Define a resource of type
- Second Resource (Report):
- Define another resource of type
local_file. - Name it
inventory_report. - Set its
filenameattribute to"report.log". - The
contentfor this file must be dynamic. It should be the string"Inventory data sourced from: "followed by the filename of theserver_inventoryresource. You must use Terraform's interpolation syntax to reference the attribute from the first resource.
- Define another resource of type
Expected result
Your code should be a single, valid Terraform configuration.
It must contain:
- A
terraformconfiguration block with a nestedrequired_providersblock. Inside, thelocalprovider should be specified with the correct source (hashicorp/local) and version constraint (~> 2.1). - A
resourceblock forlocal_file.server_inventorywith the exactfilenameand multi-linecontentas specified in the instructions. - A second
resourceblock forlocal_file.inventory_report. - The
contentattribute of theinventory_reportresource must correctly use an interpolation expression to reference thefilenameof theserver_inventoryresource. The correct syntax is${local_file.server_inventory.filename}.