DDevArchive
Đăng nhập

Infrastructure as Code: Terraform cơ bản — không click console nữa

Click tạo EC2 trên AWS Console → ai nhớ bạn click gì? Click 50 lần tạo 50 server → copy-paste nhầm 1 chỗ. Infrastructure as Code (IaC): viết file config → chạy 1 lệnh → infra được tạo chính xác, mỗi lần, mọi nơi.

IaC: vì sao không nên click console?

Click consoleInfrastructure as Code
Không ai nhớ bạn click gìConfig file trong Git → version controlled
Tạo lại = làm lại từ đầuChạy lệnh → identical environment
Sai 1 click = server lỗiCode review trước khi apply
Không test đượcterraform plan → preview thay đổi trước khi thực hiện
1 người biếtTeam đều đọc được config

Terraform cơ bản: 3 file, 3 lệnh

// File: main.tf
# main.tf — mô tả infra bạn muốn

provider "aws" {
  region = "ap-southeast-1" # Singapore
}

# Tạo VPC
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
  tags = { Name = "my-app-vpc" }
}

# Tạo EC2 instance
resource "aws_instance" "web" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t3.micro"
  tags = { Name = "my-app-web" }
}

# Tạo database RDS
resource "aws_db_instance" "db" {
  engine         = "postgres"
  engine_version = "15"
  instance_class = "db.t3.micro"
  allocated_storage = 20
  db_name        = "myapp"
  username       = var.db_username
  password       = var.db_password # từ variables, KHÔNG hardcode
}
// File: terraform-commands.sh
# 3 lệnh cốt lõi:

terraform init    # Download provider (AWS, GCP, etc)
terraform plan    # Preview: sẽ tạo/sửa/xoá gì?
terraform apply   # Thực hiện thay đổi

# Xoá toàn bộ infra (cẩn thận!)
terraform destroy

Khi nào cần IaC?

Giai đoạnCần IaC?Dùng gì
MVP, 1 server❌ KhôngClick console hoặc Vercel/Railway
2-5 servers, staging + prod⚠️ NênTerraform hoặc Pulumi
10+ servers, multi-region✅ Bắt buộcTerraform + CI/CD pipeline
💡 Alternatives nhẹ hơn

Terraform mạnh nhưng phức tạp. Nếu chỉ dùng 1 cloud: AWS CDK (TypeScript), Pulumi (TypeScript/Python). Nếu chỉ cần container: docker-compose.yml cũng là IaC ở mức đơn giản nhất.

❓ Ưu điểm lớn nhất của IaC so với click console?

  • Hiểu 3 lệnh Terraform: init, plan, apply
  • Viết 1 file main.tf tạo EC2 + RDS
  • Biết khi nào cần IaC vs khi nào click đủ
  • Biết alternatives: CDK, Pulumi, docker-compose