Terraform: Complete Tutorial from Basics to Advanced

DevOps

MOTOSHARE 🚗🏍️
Turning Idle Vehicles into Shared Rides & Earnings

From Idle to Income. From Parked to Purpose.
Earn by Sharing, Ride by Renting.
Where Owners Earn, Riders Move.
Owners Earn. Riders Move. Motoshare Connects.

With Motoshare, every parked vehicle finds a purpose. Owners earn. Renters ride.
🚀 Everyone wins.

Start Your Journey with Motoshare

Here is a detailed, beginner-to-advanced tutorial for Terraform, fully incorporating your notes and best practices from the real world.
The aim is to keep it friendly, practical, and immediately useful for engineers and platform teams.


Terraform: Complete Tutorial from Basics to Advanced


What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool by HashiCorp that lets you define, provision, and manage cloud and on-premises infrastructure using a simple, declarative language called HCL (HashiCorp Configuration Language).
You write code for infrastructure—instead of manually clicking buttons in a cloud portal.

  • Supports all major clouds: AWS, Azure, GCP, Alibaba, Oracle, VMware, and thousands more via Terraform Registry Providers
  • Works for any infra: VPC, EC2, EKS, S3, RDS, GKE, DNS, load balancers, networking, storage, and more
  • Build once, deploy everywhere: One code spec for 5000+ platforms

Terraform is written in Go.


Terraform Editions

  • Community (Open Source):
    Command line, free, most commonly used
  • Enterprise:
    Self-hosted, with GUI and governance (paid)
  • Cloud:
    Hosted by HashiCorp, with GUI, remote state, team features (free & paid tiers)

Why Use Terraform?

  • Easy to learn (especially compared to alternatives)
  • Fast to debug and test (plan before you apply)
  • Great for sharing code (modules, versioning, Git)
  • Declarative: Write what you want, not how to do it
  • Automates provisioning, updating, destroying entire environments
  • Consistent and repeatable deployments

Terraform vs. Ansible

Use CaseTerraformAnsible
Infra provisioningBest for this: create/update/destroy infraPossible, but not ideal
App config/updatesNot for updating apps or services on serversBest for this: update, patch, etc
IdempotenceAlways aims for idempotence (infra state)Idempotence, but at config level
ExampleCreate VPC, EKS, EC2, S3, DNS, etc.Update software, push configs, etc.

Summary:

  • Use Terraform for creating, modifying, and destroying infrastructure
  • Use Ansible for configuring or updating existing servers/services

How Terraform Works: The Core Workflow

1. Install Terraform

2. Organize Your Codebase

Terraform code is written in .tf files, using HCL syntax.

  • A directory = a module = a project
  • All .tf files in a directory are merged when you run terraform plan/apply/destroy
  • You cannot run a single .tf file—everything in the directory is evaluated together

Common file structure:

.
├── main.tf      # Main resources
├── variables.tf # Input variables
├── outputs.tf   # Outputs after apply
├── provider.tf  # Provider config (e.g., AWS credentials)
└── terraform.tfvars # Variable values (optional)
Code language: CSS (css)

You can also split code for clarity:

  • network.tf, compute.tf, etc.

3. Initialize Your Working Directory

Every new Terraform project needs an init:

terraform init
  • Downloads providers (AWS, Azure, GCP, etc.)
  • Prepares your directory for further commands

4. Write Your First Terraform Code

Provider example (AWS):

provider "aws" {
  region = "us-east-1"
}
Code language: JavaScript (javascript)

Resource example (EC2 instance):

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}
Code language: JavaScript (javascript)

Run core commands:

terraform validate    # Check if the configuration is valid
terraform plan        # See what will change (no infra changes yet)
terraform apply       # Apply the changes (create/update resources)
terraform destroy     # Tear down everything in the directory
Code language: PHP (php)

Terraform Lifecycle and Workflow

Full article: Terraform basics workflow loop

Typical steps:

  1. Write code (.tf files)
  2. terraform init (setup)
  3. terraform validate (lint)
  4. terraform plan (preview)
  5. terraform apply (make changes)
  6. terraform destroy (teardown)

Understanding Terraform Code: The Anatomy

Each resource or data source in Terraform code:

resource "provider_resource" "name" {
  argument1 = "value"
  argument2 = "value"
  # ...
}
Code language: PHP (php)

You’ll find the specific arguments for each resource in the Terraform provider docs.


Variables, Conditionals, and Loops

  • Variables:
    Define with variable blocks, use in code via ${var.name} or var.name
  • Conditionals:
    condition ? true_value : false_value
  • Loops:
    Use count or for_each to create multiple resources

Example:

variable "server_count" {
  default = 3
}

resource "aws_instance" "web" {
  count = var.server_count
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}
Code language: JavaScript (javascript)

Modules (Reusable Components)

A module is simply a directory of Terraform code.
Modules help you structure, reuse, and share code—like functions in programming.

Basic module structure:

modules/
  webserver/
    main.tf
    variables.tf
    outputs.tf

Usage:

module "webserver" {
  source = "./modules/webserver"
  instance_count = 3
}
Code language: JavaScript (javascript)

Real-World Terraform Project Structure

For large/production deployments, structure your repo like this:

production/
  main.tf
  variables.tf
  outputs.tf
  terraform.tfvars
  # Child modules:
  dns/
    main.tf
  ext_lb/
    main.tf
  vms_web/
    main.tf
  int_lb/
    main.tf
  vms_app/
    main.tf
  db_servers/
    main.tf
Code language: PHP (php)
  • Each subdirectory can be a module or logical grouping.

Common Terraform Commands Recap

CommandWhat it does
terraform initInitializes directory, downloads providers
terraform validateChecks for syntax and logic errors
terraform planShows the proposed changes (preview)
terraform applyMakes the changes (provisions/updates infra)
terraform destroyDeletes all resources managed in the configuration

Terraform Providers

Terraform talks to the cloud or infra APIs using providers.

  • Browse providers (AWS, Azure, GCP, GitHub, VMware, and 1000s more)
  • Provider block in provider.tf:
provider "aws" {
  region = var.aws_region
}
Code language: JavaScript (javascript)

Resource Lifecycle: CRUD

Terraform operates via the CRUD model on resources:

  • Create: Make new resources
  • Read: Check resource status/state
  • Update: Change resource properties
  • Delete: Remove resources

Variables, Outputs, Conditionals, Loops — Advanced Examples

Variable Example

variable "instance_type" {
  default = "t3.medium"
}
Code language: JavaScript (javascript)

Conditional Example

resource "aws_instance" "maybe_db" {
  count = var.create_db ? 1 : 0
  ami = "ami-xxxx"
  instance_type = "t2.micro"
}
Code language: JavaScript (javascript)

Loop Example

resource "aws_security_group_rule" "ingress" {
  count = length(var.allowed_ports)
  type        = "ingress"
  from_port   = var.allowed_ports[count.index]
  to_port     = var.allowed_ports[count.index]
  protocol    = "tcp"
  cidr_blocks = ["0.0.0.0/0"]
}
Code language: JavaScript (javascript)

When to Use Modules

  • For repeating patterns (VPCs, subnets, EC2, etc.)
  • When you need consistency and reusability
  • When building large or team-managed infrastructures

Large Deployment Example (Web App Infra)

A real-world, production-grade deployment may look like:

HUMAN (user) → DNS → External LB → Web VMs → Internal LB → App VMs → DB Servers

You’d create a parent directory (production/), with child modules for DNS, load balancers, VMs, and DBs.


Terraform Best Practices

  • Keep modules focused and reusable
  • Use remote state (Terraform Cloud, S3 + DynamoDB, etc.) for collaboration
  • Lock provider versions in code
  • Use terraform validate and terraform plan before every apply
  • Document variables and outputs
  • Separate environments (dev, staging, prod) into different directories or workspaces

Getting Hands-On: Your First Terraform Project

1. Install Terraform

Follow the official install guide.

2. Write a Basic Configuration

provider.tf:

provider "aws" {
  region = "us-east-1"
}
Code language: JavaScript (javascript)

main.tf:

resource "aws_instance" "myec2" {
  ami           = "ami-0c94855ba95c71c99" # Example Amazon Linux AMI
  instance_type = "t2.micro"
}
Code language: PHP (php)

variables.tf: (optional for inputs)

variable "aws_region" {
  default = "us-east-1"
}
Code language: JavaScript (javascript)

outputs.tf: (see instance public IP)

output "ec2_public_ip" {
  value = aws_instance.myec2.public_ip
}
Code language: JavaScript (javascript)

3. Run the Terraform Workflow

terraform init
terraform validate
terraform plan
terraform apply

You’ll see your infra created in AWS.
To tear it down:

terraform destroy

Where to Go Next

  • Terraform Registry: Find modules/providers for anything
    https://registry.terraform.io/
  • Write your own modules for reusability
  • Automate with CI/CD: Use GitHub Actions, GitLab CI, Jenkins, etc.
  • State management: Use remote state for teams
  • Security: Use tools like tfsec and checkov for static code analysis

Summary Table: Terraform at a Glance

FeatureDetails
LanguageHCL (HashiCorp Configuration Language)
Platforms5000+ (AWS, Azure, GCP, on-prem, SaaS, etc.)
EditionsCommunity (CLI), Enterprise (Self-host), Cloud
Core Commandsinit, validate, plan, apply, destroy
Key ConceptsProvider, Resource, Data, Variable, Output, Module
Advanced FeaturesLoops, Conditionals, Dynamic Blocks, Modules
Best PracticesRemote state, versioning, modularity, validation

Conclusion

Terraform makes cloud infrastructure repeatable, auditable, and scalable.
It’s the standard for DevOps and cloud engineers worldwide.

Start small, break infra into logical modules, and automate everything!


Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x