Terraform Fundamentals
Learn Terraform fundamentals including Infrastructure as Code (IaC), HCL syntax, providers, resources, variables, outputs, state management, modules, lifecycle, commands, and production best practices with real-world examples.
Introduction
Modern cloud infrastructure is no longer created manually through cloud consoles. Instead, organizations define infrastructure using code, enabling automation, repeatability, version control, and consistency.
Terraform, developed by HashiCorp, is one of the world's most popular Infrastructure as Code (IaC) tools. It allows engineers to provision and manage infrastructure across AWS, Azure, Google Cloud, Kubernetes, OpenShift, VMware, Oracle Cloud, and hundreds of other providers using simple declarative configuration files.
Terraform is widely adopted by companies like Netflix, Airbnb, Uber, Stripe, Shopify, Capital One, Adobe, and Red Hat to automate infrastructure provisioning at scale.
This guide introduces the core Terraform concepts required for DevOps, Cloud, Platform Engineering, and Solution Architect interviews.
Learning Objectives
After completing this guide, you'll understand:
- What is Terraform?
- Infrastructure as Code (IaC)
- Declarative vs Imperative
- Terraform Architecture
- Providers
- Resources
- Data Sources
- Variables
- Outputs
- Locals
- State File
- Terraform Workflow
- Modules
- Terraform Commands
- Lifecycle
- Dependency Management
- Production Best Practices
What is Infrastructure as Code?
Infrastructure as Code (IaC) means managing infrastructure using code instead of manually creating cloud resources.
Instead of logging into AWS Console and creating resources one by one, Terraform creates everything automatically.
Traditional Infrastructure
Administrator
↓
AWS Console
↓
Create VPC
↓
Create EC2
↓
Create Security Group
↓
Create Database
↓
Deploy Application
Problems
- Manual Errors
- Slow Provisioning
- Inconsistent Environments
- Difficult Rollback
- No Version Control
Infrastructure as Code
flowchart LR
Developer --> Git --> Terraform --> AWS --> Infrastructure
Benefits
- Automation
- Version Control
- Repeatability
- Faster Provisioning
- Easy Rollback
What is Terraform?
Terraform is an Infrastructure as Code tool that provisions and manages cloud resources using configuration files written in HCL (HashiCorp Configuration Language).
Terraform supports more than 2,000 providers, including:
- AWS
- Azure
- Google Cloud
- Kubernetes
- OpenShift
- VMware
- Oracle Cloud
- GitHub
- Datadog
- Cloudflare
Terraform Architecture
flowchart LR
TerraformCLI --> Provider --> CloudAPI --> Resources
Components
- Terraform CLI
- Providers
- State File
- Configuration Files
- Cloud Provider APIs
Declarative vs Imperative
| Declarative | Imperative |
|---|---|
| Define Desired State | Define Steps |
| Terraform | Shell Scripts |
| Easier Maintenance | More Manual Logic |
| Preferred for IaC | Used for Automation Scripts |
Terraform is declarative.
Terraform Workflow
flowchart LR
WriteCode --> Init --> Plan --> Apply --> Infrastructure
Steps
- Write Terraform code
- Initialize providers
- Review execution plan
- Apply changes
- Infrastructure created
Terraform Files
Common files
| File | Purpose |
|---|---|
| main.tf | Resources |
| variables.tf | Variables |
| outputs.tf | Outputs |
| providers.tf | Providers |
| terraform.tfvars | Variable Values |
Provider
A provider enables Terraform to communicate with cloud platforms.
Example
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
Resource
Resources represent infrastructure components.
Example
resource "aws_instance" "web" {
ami = "ami-123456"
instance_type = "t3.micro"
}
Examples
- EC2
- S3
- RDS
- IAM
- Lambda
- VPC
Data Source
Data Sources read existing infrastructure.
Example
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
}
Unlike resources, data sources do not create infrastructure.
Variables
Variables make Terraform reusable.
Example
variable "instance_type" {
default = "t3.micro"
}
Usage
instance_type = var.instance_type
Outputs
Outputs display useful information after deployment.
Example
output "public_ip" {
value = aws_instance.web.public_ip
}
Local Values
Locals simplify repeated expressions.
Example
locals {
environment = "dev"
}
Usage
tags = {
Environment = local.environment
}
Terraform State
Terraform stores infrastructure information inside the state file.
flowchart LR
Terraform --> StateFile
StateFile --> CloudInfrastructure
State tracks
- Created Resources
- Resource IDs
- Dependencies
- Metadata
Default state file
terraform.tfstate
Terraform Commands
Initialize project
terraform init
Format code
terraform fmt
Validate configuration
terraform validate
Generate execution plan
terraform plan
Apply changes
terraform apply
Destroy infrastructure
terraform destroy
Show state
terraform show
List resources
terraform state list
Dependency Management
Terraform automatically builds a dependency graph.
flowchart TD
VPC --> Subnet
Subnet --> EC2
EC2 --> Application
Explicit dependency
depends_on = [
aws_vpc.main
]
Modules
Modules organize reusable infrastructure.
modules/
network/
compute/
database/
security/
Benefits
- Reusability
- Standardization
- Easy Maintenance
Lifecycle Rules
Terraform supports lifecycle customization.
Example
lifecycle {
create_before_destroy = true
}
Common options
- create_before_destroy
- prevent_destroy
- ignore_changes
Provisioners
Provisioners execute scripts after resource creation.
Example
provisioner "local-exec" {
command = "echo Instance Created"
}
Provisioners should be avoided unless absolutely necessary.
Typical AWS Infrastructure
flowchart TD
Terraform --> VPC
VPC --> Subnet
Subnet --> EC2
Subnet --> RDS
EC2 --> Application
Terraform Project Structure
terraform-project/
├── main.tf
├── variables.tf
├── outputs.tf
├── providers.tf
├── terraform.tfvars
├── versions.tf
├── modules/
├── environments/
└── README.md
Common Terraform Providers
| Provider | Purpose |
|---|---|
| AWS | AWS Infrastructure |
| Azure | Azure Resources |
| GCP Resources | |
| Kubernetes | Kubernetes Objects |
| Helm | Helm Charts |
| GitHub | Repository Management |
| Cloudflare | DNS |
| Datadog | Monitoring |
Advantages
- Infrastructure as Code
- Cloud Agnostic
- Version Controlled
- Reusable
- Automated
- Scalable
- Declarative
- Strong Community
- Large Provider Ecosystem
Limitations
- State File Management
- Learning Curve
- No Built-in Secret Storage
- Provider Compatibility Issues
- Large Projects Require Good Module Design
Production Best Practices
Code
- Use Modules
- Reuse Variables
- Keep Configurations Small
- Follow Naming Standards
State
- Never commit state files to Git
- Use Remote State
- Enable State Locking
- Encrypt State Files
Security
- Store secrets in Vault or Secrets Manager
- Use IAM Roles
- Follow Least Privilege
- Enable Audit Logging
Infrastructure
- Separate environments
- Tag all resources
- Use versioned modules
- Automate validation
Real-World Example
A DevOps engineer needs to provision infrastructure for a Spring Boot application.
- Developer writes Terraform code.
- Code is committed to GitHub.
- GitHub Actions triggers Terraform.
- Terraform initializes the AWS provider.
- A VPC, subnets, security groups, EC2 instances, RDS database, and Application Load Balancer are provisioned.
- Outputs provide the application URL and database endpoint.
- The same configuration is reused across Development, QA, and Production by changing only variable values.
Interview Tips
Remember these keywords
- Infrastructure as Code
- Declarative
- HCL
- Provider
- Resource
- Data Source
- Variable
- Output
- Local
- Module
- State File
- Plan
- Apply
- Destroy
- Dependency Graph
- Lifecycle
Summary
Terraform enables teams to automate infrastructure provisioning using declarative code, making cloud environments consistent, repeatable, and version controlled. Core concepts such as providers, resources, variables, modules, state management, lifecycle rules, and dependency graphs form the foundation of every Terraform project.
Mastering these fundamentals prepares you for HashiCorp Terraform Associate certification as well as DevOps Engineer, Cloud Engineer, Platform Engineer, SRE, and Solution Architect interviews.
In the next chapter, you'll explore Terraform Advanced, including remote state, workspaces, advanced modules, CI/CD integration, policy as code, multi-cloud deployments, security, and enterprise production architectures.