Back to Blog
Lesson 49 of the System Design: System Design Fundamentals course
ArchitectureSeptember 4, 20264 min read

Introduction to Infrastructure as Code: Automate Your Cloud

Stop configuring servers by hand. Learn how to use Terraform to provision and destroy cloud infrastructure, ensuring your environments are reproducible.

IaCTerraformInfrastructureAutomationCloud
A programmer working on code with a laptop and monitor setup in an office.

Previously in this course, we covered containerization basics to ensure your application code runs the same way everywhere. However, the container is only half the battle; the infrastructure it lives on—networks, servers, and storage—must also be consistent. This is where Infrastructure as Code (IaC) comes in.

IaC is the practice of managing and provisioning your infrastructure through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools.

Why Infrastructure as Code Matters

When you provision resources manually via a web console, you invite "configuration drift"—a state where your actual infrastructure differs from what you intended. IaC solves this by treating infrastructure like software: you version it, test it, and review it.

If you are interested in deeper validation strategies, you can read more about testing infrastructure: IaC validation in CI/CD pipelines. For this lesson, we will focus on the fundamentals: using Terraform to bring a resource into existence and removing it when it’s no longer needed.

Provisioning with Terraform: A Worked Example

Men unloading a fresh catch from the boat at the dock, showcasing teamwork and marine livelihood.

We will use HashiCorp Terraform because of its provider-agnostic model and widespread industry adoption. First, install the Terraform binary on your local machine.

Create a file named main.tf. We will define a simple "null resource," which acts as a placeholder to demonstrate the lifecycle without needing a specific cloud account right now.

HCL
# main.tf
resource "null_resource" "web_server" {
  provisioner "local-exec" {
    command = "echo 'Provisioning server...'"
  }
}

The Three Stages of IaC

To work with this file, you must follow the standard Terraform workflow:

  1. Initialize: Run terraform init. This downloads the necessary provider plugins.
  2. Plan: Run terraform plan. This compares your current state (which is empty) to your desired state (main.tf) and lists the changes.
  3. Apply: Run terraform apply. This executes the changes against the real infrastructure.

When you run terraform apply, Terraform creates a terraform.tfstate file. This file is critical; it is the "source of truth" that records what Terraform has already deployed.

Destroying Infrastructure Safely

One of the greatest benefits of IaC is the ability to tear down environments as easily as you create them. This is vital for cost management and testing.

To remove the resource we just created, simply run: terraform destroy

Terraform will reference the terraform.tfstate file, determine which resources were previously created, and issue the necessary commands to delete them in the correct dependency order.

Hands-on Exercise: Manage a File

Let’s move beyond the null resource. Create a new directory and a main.tf file that uses the local provider to create a file on your disk.

  1. Define a local_file resource in your main.tf:
    HCL
    resource "local_file" "config" {
      content  = "server_ip=127.0.0.1"
      filename = "${path.module}/server_config.txt"
    }
  2. Run terraform init and terraform apply. Verify that server_config.txt exists in your folder.
  3. Change the content string in main.tf to "server_ip=10.0.0.1".
  4. Run terraform apply again. Notice how Terraform detects the change and updates the file content instead of destroying and recreating the resource unnecessarily.
  5. Run terraform destroy to clean up.

Common Pitfalls

  • Committing State Files: Never commit terraform.tfstate to version control. It often contains sensitive data like API keys. Use a .gitignore file.
  • Manual Changes: If you manually change a resource in the cloud console after using Terraform, your state file will become "stale." This is known as configuration drift; you can learn more about managing this with drift detection.
  • Resource Dependency: Always define dependencies explicitly if Terraform doesn't automatically detect them to ensure resources are created in the right order (e.g., a database before the application server).

FAQ

Q: Is Terraform the only IaC tool? A: No. AWS CloudFormation, Pulumi, and Ansible are also widely used. Terraform is often preferred for its cross-cloud capabilities.

Q: What if my apply fails midway? A: Terraform is designed to be idempotent. You can fix the error in your code and run terraform apply again; it will attempt to reach the desired state from its last known position.

Recap

Infrastructure as Code allows us to treat our cloud footprint as an extension of our codebase. By using Terraform, we move from "click-ops" to repeatable, version-controlled provisioning. We’ve covered initialization, planning, applying, and the safe destruction of resources.

Up next: We will integrate these concepts into a production-grade workflow in our lesson on CI/CD Pipeline Fundamentals.

Similar Posts