Learn Terraform · 1/11

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?

  1. It's not repeatable: If you need to build the exact same environment for "Staging," you have to remember every single click.
  2. Human Error: You will forget to tick that one security box, and suddenly your database is mining crypto for a stranger in a basement.
  3. 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 apply a 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.

bash
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

🪟 Windows (Chocolatey)

Run your PowerShell as Administrator:

powershell
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.

bash
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 terraform

Verify installation:
Type this in your terminal. If you see a version number, you win.

bash
terraform -version

Step B: Editor Configuration

We are using VS Code (Visual Studio Code). It is the industry standard for Terraform.

  1. Open VS Code.
  2. Go to the Extensions Marketplace (Block icon on the left).
  3. Search for "HashiCorp Terraform".
  4. 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:

  1. Provider: The plugin that talks to the API (e.g., AWS, Azure, or your local filesystem).
  2. 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:

hcl
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 it pizza, server, or bob. 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.

bash
terraform init

What 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:

bash
terraform plan

What 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 file pets.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:

bash
terraform apply

Terraform will show the plan again and ask for confirmation. Type yes.

What happened?

  1. The file pets.txt was created in your folder. Go check it!
  2. Terraform created a file called terraform.tfstate.

Under the Hood (Important!): The terraform.tfstate file 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:

bash
terraform destroy

Type yes to confirm.

What happened?
Terraform looked at its state file, found the file it created, and deleted it.


🎯 Summary

  1. IaC solves the problem of manual, error-prone "ClickOps."
  2. Terraform is a declarative tool: you say what you want, it figures out how.
  3. 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:

  1. Terraform Block: Declare that the configuration requires the local provider from the hashicorp/local source, version ~> 2.1.
  2. First Resource (Inventory):
    • Define a resource of type local_file.
    • Name it server_inventory.
    • Set its filename attribute to "inventory.txt".
    • Set its content to the following multi-line string:
      nginx
      # Server List
      web_server_01
      db_server_01
      app_server_01
  3. Second Resource (Report):
    • Define another resource of type local_file.
    • Name it inventory_report.
    • Set its filename attribute to "report.log".
    • The content for this file must be dynamic. It should be the string "Inventory data sourced from: " followed by the filename of the server_inventory resource. You must use Terraform's interpolation syntax to reference the attribute from the first resource.

Expected result

Your code should be a single, valid Terraform configuration.

It must contain:

  1. A terraform configuration block with a nested required_providers block. Inside, the local provider should be specified with the correct source (hashicorp/local) and version constraint (~> 2.1).
  2. A resource block for local_file.server_inventory with the exact filename and multi-line content as specified in the instructions.
  3. A second resource block for local_file.inventory_report.
  4. The content attribute of the inventory_report resource must correctly use an interpolation expression to reference the filename of the server_inventory resource. The correct syntax is ${local_file.server_inventory.filename}.
terraform

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.