Infrastructure as Code Fundamentals & Terraform Basics
Clicking through cloud dashboards to create servers, databases, and networks works fine for a small test project. But when you need to build identical environments for development, staging, and production, manual clicking leads to human errors and configuration drift.
Infrastructure as Code (IaC) solves this problem by letting you define your entire infrastructure in simple text files. In this guide, you will learn how Terraform works and build a real local lab using Docker—without spending a single rupee on cloud bills.
- What declarative Infrastructure as Code (IaC) means and why teams rely on it.
- How to read and write HCL (HashiCorp Configuration Language) syntax.
- How Terraform providers connect your code to tools like Docker, AWS, or Azure.
- The core Terraform workflow:
init,plan,apply, anddestroy. - Hands-on lab: Installing Terraform and Docker locally to provision a real container and network.
1. What Is Declarative Infrastructure as Code?
Infrastructure as Code means managing your servers, networks, and containers using code files instead of manual setup. You can store these files in Git, review them with your team, and run them repeatedly to get the exact same setup every time.
Terraform uses a declarative approach. Instead of writing step-by-step instructions on how to build something, you simply describe what the final result should look like. Terraform figures out the steps on its own.
| Approach | How It Works | Real-World Example | Tools |
|---|---|---|---|
| Declarative (What) | You describe the desired end state. The tool figures out how to reach it. | "I want 1 Docker network and 1 Nginx container running on port 8080." | Terraform, CloudFormation |
| Imperative (How) | You write exact step-by-step commands in the right order. | "Step 1: Pull image. Step 2: Create network. Step 3: Start container." | Bash scripts, AWS CLI |
2. Understanding HCL Syntax and Providers
Terraform files end with the .tf extension and are written in HCL (HashiCorp Configuration Language). HCL is designed to be easy for humans to read and easy for machines to process.
Every HCL file is made up of blocks and arguments:
- Block: A container for configuration, defined with curly braces
{ }. Common blocks areterraform,provider, andresource. - Arguments: Key-value pairs inside a block that configure settings (for example,
name = "my-app-network"). - Providers: Plugins that let Terraform talk to external platforms. Want to build on AWS? Use the AWS provider. Want to run containers locally? Use the Docker provider.
3. The Core Terraform Workflow Visualized
Whether you are spinning up a tiny local Docker container or a massive 500-server Kubernetes cluster on AWS, you will always follow the exact same five-step Terraform lifecycle.
Core Terraform Lifecycle Workflow
Terraform compares your written HCL code against the terraform.tfstate file during Plan, applies changes to real infrastructure, and cleans everything up during Destroy.
4. Hands-On Lab: Provisioning a Local Docker Container
Let's put theory into practice. We will install Terraform and Docker locally, write a main.tf file, and spin up an Nginx web server inside a custom Docker network.
Step A: Install Prerequisites
- Install Docker Desktop: Download and install Docker Desktop for Windows or macOS, then start it so the Docker engine is running in the background.
- Install Terraform CLI: Download the free binary from HashiCorp or install it via your package manager:
- Windows (Winget):
winget install Hashicorp.Terraform - macOS (Homebrew):
brew tap hashicorp/tap && brew install hashicorp/tap/terraform
- Windows (Winget):
- Verify installation: Open your terminal and run
terraform -versionanddocker -version.
Step B: Write Your main.tf File
Create a new folder named terraform-docker-lab, open it in VS Code, and create a file called main.tf with the following code:
main.tf: Provisioning a Docker network and Nginx container
# 1. Tell Terraform which provider plugin we need
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 3.0.1"
}
}
}
# 2. Configure the Docker provider (connects to local Docker automatically)
provider "docker" {}
# 3. Create a custom local Docker network
resource "docker_network" "app_network" {
name = "upgradix_lab_network"
}
# 4. Pull the latest Nginx image from Docker Hub
resource "docker_image" "nginx" {
name = "nginx:latest"
keep_locally = false
}
# 5. Create and start the Nginx container attached to our network
resource "docker_container" "web_server" {
image = docker_image.nginx.image_id
name = "upgradix_nginx_server"
networks_advanced {
name = docker_network.app_network.name
}
ports {
internal = 80
external = 8080
}
}
Step C: Initialize the Project (terraform init)
Run terraform init in your terminal. This reads your required_providers block and downloads the Docker provider plugin into a hidden .terraform folder.
Command & Expected output
$ terraform init Initializing the backend... Initializing provider plugins... - Finding kreuzwerker/docker versions matching "~> 3.0.1"... - Installing kreuzwerker/docker v3.0.2... - Installed kreuzwerker/docker v3.0.2 Terraform has been successfully initialized!
Step D: Preview the Changes (terraform plan)
Run terraform plan to see what Terraform intends to create before making any real changes. This is your safety net.
Command & Expected output
$ terraform plan
Terraform will perform the following actions:
# docker_container.web_server will be created
+ resource "docker_container" "web_server" { ... }
# docker_image.nginx will be created
+ resource "docker_image" "nginx" { ... }
# docker_network.app_network will be created
+ resource "docker_network" "app_network" { ... }
Plan: 3 to add, 0 to change, 0 to destroy.
Step E: Build the Infrastructure (terraform apply)
Run terraform apply. Terraform will show the plan again and ask for confirmation. Type yes and press Enter.
Command & Expected output
$ terraform apply ... Do you want to perform these actions? Enter a value: yes docker_network.app_network: Creation complete after 0s docker_image.nginx: Creation complete after 6s docker_container.web_server: Creation complete after 1s Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
Open your browser and visit http://localhost:8080. You will see the live "Welcome to nginx!" page running inside your Terraform-managed Docker container.
Step F: Clean Up Everything (terraform destroy)
When you finish testing, run terraform destroy and type yes. Terraform will stop the container, remove the image, and delete the network cleanly.
Command & Expected output
$ terraform destroy ... Do you really want to destroy all resources? Enter a value: yes docker_container.web_server: Destruction complete after 1s docker_image.nginx: Destruction complete after 0s docker_network.app_network: Destruction complete after 0s Destroy complete! Resources: 3 destroyed.
5. Step-by-Step Execution Breakdown
Notice how we did not tell Terraform to create the network before the container, yet it did so automatically. Here is what happened under the hood:
docker_container.web_server referenced docker_network.app_network.name and docker_image.nginx.image_id, Terraform automatically knew it had to create the network and pull the image first.terraform apply, Terraform created a file called terraform.tfstate in your folder. This JSON file maps your HCL resource names to the real Docker container and network IDs.terraform apply a second time without changing main.tf, Terraform checks the state file, sees that everything already matches, and makes zero changes.terraform.tfstate to a public Git repository. In real cloud projects, state files can contain sensitive data like database passwords and API keys. In production, teams store state securely in remote backends like AWS S3 with DynamoDB state locking.6. Hands-On Practice
Modify your main.tf file so the Nginx container runs on port 9090 instead of 8080. Run terraform plan and observe how Terraform handles the change.
Hint: Look at the ports block inside docker_container. Notice whether Terraform updates the container in place or destroys and recreates it.
Add a second docker_container resource named web_server_2 running on port 8081 and attach it to the same upgradix_lab_network.
Expected result: Running terraform apply should report 1 added, 0 changed, 0 destroyed, and both localhost:8080 and localhost:8081 should load Nginx.
After running terraform apply, manually stop and delete the container using the Docker CLI (docker rm -f upgradix_nginx_server). Then run terraform plan.
Hint: Watch how Terraform detects that the real-world infrastructure drifted from your code and automatically plans to recreate the missing container.
7. Terraform Basics – Interview Questions
Answer: Declarative IaC (like Terraform) defines the desired end state of the infrastructure, and the tool determines the steps to achieve it. Imperative IaC (like Bash scripts) requires you to write the exact step-by-step commands in the correct order.
Answer: The state file tracks the real-world resources created by Terraform and maps them to your HCL configuration. Without it, Terraform would not know what already exists, what needs to be updated, or what to delete during terraform destroy.
Answer: terraform plan acts as a dry run. It compares your code against the current state and shows you exactly which resources will be added, modified, or destroyed—preventing accidental production outages before any real changes happen.
Conclusion
You have just learned the foundation of modern cloud engineering. By defining your infrastructure in HCL and using the init, plan, apply, and destroy workflow, you can build repeatable, version-controlled environments on any platform.
Once you are comfortable provisioning local Docker containers, switching to AWS, Azure, or Google Cloud is simply a matter of changing the provider block and resource names. Have you built a cool local Terraform lab? Head over to Upgradix by Shrash Studio, share your configuration, and earn goodies for helping the community grow!
Official Documentation
Upgradix by Shrash Studio – Learn Technology. Build Your Future.
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.