Terraform — Infrastructure As Code Cho Developer Hiện Đại
Terraform giúp quản lý hạ tầng (AWS, Cloudflare, GCP) bằng code. State management, module, workspace, best practices cho developer.
Trước đây, quản lý hạ tầng là mở web console → click → nhập → nhớ. Mỗi server là một “snowflake” — cấu hình riêng, không ai dám chạm. Terraform thay đổi tất cả: hạ tầng là code, phiên bản hoá được, review được, tái tạo được.
Terraform Là Gì?#
Terraform là Infrastructure as Code (IaC) tool của HashiCorp. Bạn định nghĩa tài nguyên (VM, database, DNS, CDN) trong file HCL, Terraform biến chúng thành hiện thực.
main.tf
|
v
Terraform plan → Terraform apply
|
v
AWS / Cloudflare / GCP / AzureplaintextThay vì click 20 lần trong console để setup một server + database + DNS — bạn viết 30 dòng code và chạy terraform apply.
Tại Sao IaC?#
| Trước đây | Với Terraform |
|---|---|
| Click UI, không lưu lịch sử | Code trong Git, full audit trail |
| Cấu hình “snowflake” khác nhau | Môi trường giống hệt nhau |
| Rollback = click ngược | git revert + terraform apply |
| Setup mất vài giờ | terraform apply vài phút |
| Sợ xoá instance | Destroy và recreate dễ dàng |
HCL Cơ Bản#
Terraform dùng HCL (HashiCorp Configuration Language) — declarative, đọc được bằng tiếng Anh:
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-southeast-1"
}
resource "aws_instance" "web" {
ami = "ami-0c55..."
instance_type = "t3.micro"
tags = {
Name = "web-server"
}
}hclChạy:
terraform init # Tải provider
terraform plan # Xem những gì sẽ thay đổi
terraform apply # Thực thibashState Management#
Terraform lưu trạng thái hạ tầng hiện tại trong state file. State là trái tim của Terraform — nó biết resource nào đã tồn tại, resource nào cần tạo.
{
"version": 4,
"resources": [{
"type": "aws_instance",
"name": "web",
"instances": [{
"attributes": {
"id": "i-123456",
"public_ip": "54.123.45.67"
}
}]
}]
}jsonKhông bao giờ lưu state local. Dùng remote backend:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "ap-southeast-1"
}
}hclHoặc dùng Terraform Cloud / Cloudflare R2 / GCS.
Module — Tái Sử Dụng#
Module là package Terraform. Thay vì copy-paste, bạn gọi module:
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
}
module "web_app" {
source = "./modules/web-app"
vpc_id = module.vpc.vpc_id
subnet_ids = module.vpc.public_subnets
}hclModule có thể từ registry, GitHub, hoặc local path.
Workspace — Nhiều Môi Trường#
Dùng workspace để quản lý dev / staging / prod:
terraform workspace new dev
terraform workspace new staging
terraform workspace new prod
terraform workspace select dev
terraform applybashresource "aws_instance" "web" {
instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"
}hclVí Dụ: Cloudflare + AWS#
# Cloudflare DNS + AWS EC2
provider "cloudflare" {
api_token = var.cloudflare_token
}
provider "aws" {
region = "ap-southeast-1"
}
resource "aws_instance" "app" {
ami = "ami-0c55..."
instance_type = "t3.micro"
tags = { Name = "my-app-${terraform.workspace}" }
}
resource "cloudflare_record" "app" {
zone_id = var.cloudflare_zone_id
name = "app"
value = aws_instance.app.public_ip
type = "A"
proxied = true
}hclChạy terraform apply — Terraform tạo VM trên AWS và thêm DNS record trên Cloudflare trong một lần.
Variables Và Outputs#
# variables.tf
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.micro"
}
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Must be dev, staging, or prod."
}
}
# outputs.tf
output "public_ip" {
value = aws_instance.web.public_ip
description = "Public IP of web server"
}hclterraform apply -var="instance_type=t3.large" -var="environment=prod"bashBest Practices#
- Remote state + locking
State backend + dynamodb lock để tránh conflict:
backend "s3" {
bucket = "tf-state"
key = "prod/terraform.tfstate"
region = "ap-southeast-1"
dynamodb_table = "tf-lock"
}hcl- Module hoá
Chia thành: modules/vpc, modules/database, modules/app.
- Git workflow
main # Môi trường prod
├── staging # Môi trường staging
├── dev # Môi trường devbashApply trong CI/CD, không apply local.
- Lifecycle rules
resource "aws_db_instance" "main" {
lifecycle {
prevent_destroy = true # Không cho terraform destroy
}
}hcl- Import existing resources
Có resource đã tạo tay? Import vào state:
terraform import aws_instance.web i-123456bashSo Sánh Với Các IaC Khác#
| Terraform | Pulumi | CloudFormation | |
|---|---|---|---|
| Language | HCL | Python/TS/Go | JSON/YAML |
| State | Remote backend | Managed | AWS quản lý |
| Multi-cloud | AWS, GCP, Azure, CF | AWS, GCP, Azure | AWS only |
| Learning curve | Trung bình | Thấp (nếu biết ngôn ngữ) | Cao |
| Community | Lớn nhất | Đang phát triển | AWS ecosystem |
Kết Luận#
Terraform là kỹ năng bắt buộc nếu bạn làm backend hoặc DevOps năm 2026. Git cho code, Terraform cho hạ tầng — hai thứ không thể thiếu.
Bắt đầu: một EC2 instance + Cloudflare DNS. Module hoá khi cần tái sử dụng. Remote state + locking cho team. CI/CD cho apply tự động.