Back to Blog
Infrastructure as Code with Terraform for Laravel
Why Infrastructure as Code?
Manual infrastructure setup is error-prone and undocumented. Infrastructure as Code makes infrastructure reproducible, version-controlled, and reviewable.
Basic Terraform Structure
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
# variables.tf
variable "aws_region" {
default = "us-east-1"
}
variable "environment" {
default = "production"
}
EC2 Instance
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.medium"
vpc_security_group_ids = [aws_security_group.web.id]
key_name = aws_key_pair.deployer.key_name
root_block_device {
volume_size = 50
volume_type = "gp3"
}
tags = {
Name = "${var.environment}-web"
Environment = var.environment
}
}
RDS Database
resource "aws_db_instance" "mysql" {
identifier = "${var.environment}-mysql"
engine = "mysql"
engine_version = "8.0"
instance_class = "db.t3.medium"
allocated_storage = 100
db_name = "laravel"
username = var.db_username
password = var.db_password
vpc_security_group_ids = [aws_security_group.database.id]
db_subnet_group_name = aws_db_subnet_group.main.name
backup_retention_period = 7
multi_az = true
skip_final_snapshot = false
tags = {
Environment = var.environment
}
}
Applying Infrastructure
# Initialize Terraform
terraform init
# Preview changes
terraform plan
# Apply changes
terraform apply
# Destroy when needed
terraform destroy
State Management
# Backend for remote state
terraform {
backend "s3" {
bucket = "terraform-state-bucket"
key = "laravel/production/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
Conclusion
Terraform makes infrastructure reproducible and version-controlled. Start with basic resources, use modules for reusability, and store state remotely for team collaboration.
Related Articles
Need Help With Your Project?
I respond to all inquiries within 24 hours. Let's discuss how I can help build your production-ready system.
Get In Touch