Skip to main content

Terraform Basics: Infrastructure as Code for Beginners

· 2 min read
Goel Academy
DevOps & Cloud Learning Hub

Terraform by HashiCorp is one of the most popular Infrastructure as Code (IaC) tools. This guide will help you understand the basics and get started with your first Terraform project.

What is Terraform?

Terraform is an open-source infrastructure as code software tool that enables you to safely and predictably create, change, and improve infrastructure.

Key Concepts

  • Providers: Plugins that Terraform uses to manage resources (AWS, Azure, GCP, etc.)
  • Resources: The infrastructure components you want to create
  • State: Terraform's record of your managed infrastructure
  • Modules: Reusable Terraform configurations

Why Use Terraform?

  1. Multi-Cloud Support: Manage resources across multiple cloud providers
  2. Version Control: Track infrastructure changes in Git
  3. Reproducibility: Create identical environments consistently
  4. Collaboration: Teams can work together on infrastructure

Getting Started

Installation

# macOS with Homebrew
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

# Verify installation
terraform version

Your First Configuration

Create a file named main.tf:

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}

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

resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"

tags = {
Name = "HelloWorld"
}
}

Basic Commands

# Initialize the working directory
terraform init

# Preview changes
terraform plan

# Apply changes
terraform apply

# Destroy resources
terraform destroy

Best Practices

  1. Use remote state: Store state in S3, Azure Blob, or Terraform Cloud
  2. Use variables: Make configurations reusable
  3. Use modules: Organize and reuse code
  4. Enable state locking: Prevent concurrent modifications

Conclusion

Terraform is a powerful tool for managing infrastructure as code. Start with simple configurations and gradually adopt more advanced features as you become comfortable with the basics.