Terraform Infrastructure as Code: Complete Beginner Guide

Terraform Infrastructure as Code helps engineers create and manage cloud infrastructure through configuration files instead of manually creating resources through a cloud console.

Terraform can manage AWS, Azure, Google Cloud, Kubernetes, GitHub, and many other platforms through providers. Its core workflow is Write, Plan, and Apply.

What Is Infrastructure as Code?

Infrastructure as Code, or IaC, means defining infrastructure in code.

Instead of manually creating an EC2 instance, VPC, database, or load balancer, you describe the required infrastructure in configuration files.

IaC provides:

  • Repeatable deployments
  • Version-controlled infrastructure
  • Consistent environments
  • Faster provisioning
  • Easier collaboration
  • Reduced manual errors

What Is Terraform?

Terraform is an Infrastructure as Code tool developed by HashiCorp. It allows engineers to build, modify, and manage cloud and on-premises resources using human-readable configuration files.

Terraform uses HashiCorp Configuration Language, commonly called HCL. HCL is declarative: you describe the infrastructure you want, and Terraform determines how to create it.

Terraform can perform three major infrastructure operations:

  • Create: Provision new resources
  • Update: Modify existing resources
  • Destroy: Remove resources that are no longer required

Why Is Terraform Used in DevOps?

Terraform helps DevOps and cloud teams automate infrastructure provisioning.

Common use cases include:

  • Creating AWS VPCs and subnets
  • Launching EC2 instances
  • Creating S3 buckets
  • Deploying RDS databases
  • Configuring security groups
  • Provisioning load balancers
  • Creating EKS clusters
  • Managing DNS and SaaS resources

Terraform supports reusable modules and many infrastructure providers, making it useful for cloud, multi-cloud, and hybrid environments.

How Terraform Works

Terraform communicates with cloud platforms through APIs.

The process is:

  1. Write the desired infrastructure in .tf files.
  2. Terraform loads the required provider.
  3. Terraform compares the configuration, state, and real infrastructure.
  4. Terraform generates an execution plan.
  5. After approval, Terraform creates, updates, or deletes resources.

Core Terraform Workflow

1. Write

Define infrastructure using HCL.

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type

  tags = {
    Name = "terraform-web"
  }
}

2. Plan

terraform plan

terraform plan previews the proposed changes without applying them. Engineers should review the plan before approving infrastructure changes.

3. Apply

terraform apply

terraform apply executes the approved plan and creates, updates, or destroys infrastructure. For automated pipelines, save the reviewed plan and apply that exact plan file.

Important Terraform Components

Provider

A provider is a plugin that allows Terraform to communicate with an API.

Examples:

  • AWS
  • Azure
  • Google Cloud
  • Kubernetes
  • GitHub

Every Terraform-managed resource belongs to a provider.

Resource

A resource block creates or manages infrastructure.

resource "aws_s3_bucket" "logs" {
  bucket = "company-application-logs"
}

Data Source

A data source reads existing information without creating a resource.

For example, it can retrieve an existing VPC, subnet, account ID, or machine image.

Variables

Variables make Terraform configurations reusable.

variable "instance_type" {
  type    = string
  default = "t3.micro"
}

Values can come from:

  • terraform.tfvars
  • *.auto.tfvars
  • Environment variables
  • -var or -var-file
  • HCP Terraform variables

Outputs

Outputs display or share useful resource information.

output "public_ip" {
  value = aws_instance.web.public_ip
}

Modules

A module is a reusable collection of Terraform resources.

For example, a VPC module could create:

  • VPC
  • Public and private subnets
  • Route tables
  • Internet gateway
  • NAT gateway

Modules reduce duplicate code and standardize deployments.

Recommended Terraform File Structure

terraform-project/
├── versions.tf
├── providers.tf
├── main.tf
├── variables.tf
├── terraform.tfvars
├── outputs.tf
├── backend.tf
└── modules/

Terraform evaluates all .tf files in the same module together. Separate filenames mainly improve readability and maintenance.

Important Terraform Commands

terraform version
terraform fmt
terraform init
terraform validate
terraform plan
terraform apply
terraform show
terraform output
terraform state list
terraform import
terraform destroy

Important meanings:

  • terraform fmt — Formats Terraform code
  • terraform init — Downloads providers and modules
  • terraform validate — Checks configuration syntax
  • terraform plan — Previews infrastructure changes
  • terraform apply — Applies infrastructure changes
  • terraform state list — Lists state-managed resources
  • terraform import — Adds existing resources to Terraform state
  • terraform destroy — Removes managed infrastructure

What Is Terraform State?

Terraform state maps configuration blocks to real infrastructure resources.

By default, Terraform stores state in terraform.tfstate. Terraform uses it to:

  • Track managed resources
  • Detect infrastructure changes
  • Understand dependencies
  • Generate accurate plans
  • Avoid recreating existing resources

Terraform state can contain infrastructure details and sensitive values, so it must be protected.

Local State vs. Remote State

Local state

State is stored on the engineer’s computer.

This may be acceptable for temporary learning environments, but it is not suitable for team-based production infrastructure.

Remote state

State is stored in a shared backend such as:

  • Amazon S3
  • Azure Storage
  • Google Cloud Storage
  • HCP Terraform

For AWS production environments:

  • Enable S3 encryption
  • Enable S3 versioning
  • Restrict bucket access
  • Enable state locking
  • Never commit state files to Git

Current Terraform supports S3 lockfiles through use_lockfile = true. DynamoDB-based S3 locking is deprecated in current Terraform documentation.

Terraform State Security

Do not hardcode:

  • AWS access keys
  • Database passwords
  • API tokens
  • Private keys

Use IAM roles, workload identity, OIDC, environment variables, or a secrets-management platform.

Marking a variable as sensitive hides it from normal CLI output, but the value may still exist in state. Therefore, state encryption and access control remain necessary.

Terraform and Git

Store Terraform configuration files in Git—not in an S3 bucket.

Git provides:

  • Version history
  • Pull-request reviews
  • Branch protection
  • Change tracking
  • Rollback capability

Exclude these files from Git:

.terraform/
*.tfstate
*.tfstate.*
*.tfplan
crash.log
*.tfvars

Do not exclude .terraform.lock.hcl; commit it so provider selections remain consistent.

Terraform in CI/CD

A production pipeline commonly runs:

terraform fmt -check
terraform init
terraform validate
terraform plan
security scanning
manual approval
terraform apply

The plan should be reviewed before the apply stage. Infrastructure code can also be checked with tools such as TFLint and Checkov. AWS recommends version control, security controls, remote backends, structured code, and provider-version management.

Terraform Lifecycle Rules

create_before_destroy

Creates the replacement resource before deleting the existing resource.

Useful when replacement must minimize downtime.

prevent_destroy

Blocks accidental destruction of critical resources.

Useful for production databases and important storage.

ignore_changes

Tells Terraform not to manage selected attribute changes.

Use carefully because excessive use can hide configuration drift.

Count vs. For_Each

Use count when creating multiple nearly identical resources.

count = 3

Use for_each when resources need stable names or different configurations.

for_each = {
  web = "t3.micro"
  api = "t3.small"
}

For long-lived resources, for_each is often safer because each resource has a stable key.

What Is Infrastructure Drift?

Infrastructure drift happens when real infrastructure no longer matches Terraform configuration.

Example:

An engineer changes an EC2 instance type manually through the AWS Console, but the Terraform code still contains the old instance type.

Run terraform plan to identify the difference. Then either:

  • Update the code to accept the change
  • Apply Terraform to restore the declared configuration
  • Import an unmanaged resource where appropriate

Terraform Import

Terraform import brings an existing resource under Terraform state management.

terraform import aws_s3_bucket.logs existing-bucket-name

Import does not automatically make every existing resource correctly managed by your configuration. You must ensure that matching resource configuration exists. Terraform also supports configuration-driven import workflows.

Terraform vs. Ansible

Terraform:

  • Provisions infrastructure
  • Creates networks, servers, databases, and cloud services
  • Uses declarative HCL
  • Maintains state

Ansible:

  • Configures operating systems and applications
  • Installs packages
  • Updates configuration files
  • Performs patching and deployment tasks

A common workflow is:

  1. Terraform creates the infrastructure.
  2. Ansible configures the servers and applications.

Common Terraform Errors

No Valid Credential Sources Found

Cause: AWS credentials are missing or invalid.

Check:

aws sts get-caller-identity

Prefer an IAM role, workload identity, or short-lived credentials over permanent access keys.

Provider Not Installed

terraform init

Use terraform init -upgrade only when you intentionally want to update allowed provider versions.

Resource Already Exists

Import the existing resource instead of attempting to create a duplicate:

terraform import RESOURCE_ADDRESS RESOURCE_ID

Invalid CIDR Block

Use valid CIDR notation:

10.0.0.0/16
10.0.1.0/24

State Lock Error

Confirm that no other Terraform operation is running before using:

terraform force-unlock LOCK_ID

Never force-unlock an active operation because concurrent updates can damage state.

Unknown Variable

Define the variable or supply its value:

terraform plan -var="environment=dev"

Terraform Production Best Practices

  • Keep Terraform code in Git.
  • Use remote encrypted state.
  • Enable state versioning and locking.
  • Use least-privilege IAM roles.
  • Pin tested Terraform, provider, and module versions.
  • Run fmt, validate, and plan before applying.
  • Review every production plan.
  • Use modules for reusable infrastructure.
  • Separate development and production state.
  • Never manually edit state unless performing a controlled recovery.
  • Scan code for security problems.
  • Avoid unnecessary -auto-approve usage.
  • Avoid making manual console changes.

Best Terraform Project for Job Seekers

Build a highly available AWS environment containing:

  • VPC
  • Public and private subnets
  • Internet and NAT gateways
  • Security groups
  • Application Load Balancer
  • Auto Scaling Group
  • EC2 instances
  • RDS database
  • S3 remote state
  • Variables and outputs
  • Reusable modules
  • CI/CD validation pipeline

Be ready to explain:

  • Why remote state was used
  • How state locking works
  • How secrets were protected
  • How modules improved reusability
  • How development and production were separated
  • How the plan was reviewed before deployment

Important Terraform Interview Questions

What is Terraform?

Terraform is an Infrastructure as Code tool used to build, update, and manage infrastructure through declarative configuration files.

What is Terraform state?

State maps Terraform configuration to real resources and helps Terraform calculate required infrastructure changes.

What is the difference between plan and apply?

terraform plan previews changes. terraform apply executes the approved changes.

What is a provider?

A provider is a plugin that allows Terraform to communicate with a cloud platform, service, or API.

What is a module?

A module is a reusable collection of Terraform configurations.

What is infrastructure drift?

Drift occurs when real infrastructure differs from Terraform configuration.

Why use remote state?

Remote state supports collaboration, centralized storage, encryption, versioning, and locking.

Terraform or Ansible?

Terraform primarily provisions infrastructure. Ansible primarily configures systems and applications.

Final Takeaway

Terraform Infrastructure as Code allows DevOps and cloud engineers to create consistent, reusable, and version-controlled infrastructure.

For jobs and interviews, focus on:

  • Write, Plan, and Apply
  • Providers and resources
  • Variables and outputs
  • Modules
  • State management
  • Remote backends
  • Import and drift
  • Security
  • Practical AWS projects

Do not only memorize commands. Practice creating, updating, importing, troubleshooting, and safely destroying infrastructure.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top