Terraform Infrastructure as Code: Beginner's Guide
Terraform is HashiCorp's infrastructure as code (IaC) tool, supporting all major cloud platforms.
1. Installation
# macOS
brew install terraform
terraform version
terraform init # Initialize project
terraform plan # Preview changes
terraform apply # Apply changes
terraform destroy # Destroy resources
2. First Configuration
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = { Name = "WebServer" }
}
3. Core Concepts
| Concept | Description |
|---|---|
| Provider | Cloud platform plugin (AWS, Azure, GCP) |
| Resource | Managed resource (instance, network, etc.) |
| Data Source | Query existing resource info |
| State | Infrastructure state file (terraform.tfstate) |
| Module | Reusable configuration module |
4. State Management
Remote state storage is best practice:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
5. Variables and Outputs
# variables.tf
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
# outputs.tf
output "instance_ip" {
value = aws_instance.web.public_ip
}