Infrastructure as Code
Mở đầu
Bạn từng gặp ác mộng: server prod chết, không ai nhớ config ban đầu thế nào? Manual SSH, gõ command theo memory, cầu trời không gõ sai — đây là ops traditional. IaC (Infrastructure as Code) thay đổi: dùng code define + manage infra, để config server như software — version-controlled, reproducible, auditable.
Bạn sẽ học:
- Core concept: IaC + sao nó là foundation ops hiện đại
- Workflow: Terraform Write → Plan → Apply → Destroy
- Tool selection: Terraform, Pulumi, CloudFormation
- Risk: config drift detect + prevent
- Best practice: engineering management
| Chương | Nội dung |
|---|---|
| 1 | IaC concept |
| 2 | Terraform workflow |
| 3 | Tool comparison |
| 4 | Config drift |
| 5 | Best practice |
0. Toàn cảnh: sao infra cần "source code"?
Tưởng bạn là đầu bếp. Mỗi món nấu theo cảm giác — hôm nay 1 muỗng muối, mai 2 muỗng — taste không stable. Nhưng ghi recipe — chính xác từng gam — ai cũng reproduce được.
Infra management same. 1 server config có thể vài chục param (OS, network, security group, volume, env var). Manual config dễ sai, không reproducible, không auditable, không rollback.
IaC core value
- Reproducible: cùng code, run bao nhiêu lần kết quả như nhau (idempotency)
- Version-controlled: infra change qua Git, ai sửa gì, sao sửa rõ
- Auditable: mọi change có record, đáp ứng compliance
- Automatable: qua CI/CD auto deploy, loại risk thao tác người
- Collaborative: team review infra change qua PR, như review code
1. IaC concept
Ops traditional: login cloud console, manual click create server, config network, set security group. Vài server OK, hàng chục-trăm → ác mộng.
IaC core: dùng declarative code mô tả desired infra state, tool tự implement. Không bảo "tạo VPC, tạo subnet, tạo SG" (imperative), chỉ bảo "tôi muốn network env này" (declarative), tool tự tính step.
| 对比维度 | 手动运维 | 基础设施即代码 |
|---|---|---|
| 可重复性 | 每次操作可能不同 | 代码保证完全一致 |
| 速度 | 分钟到小时级 | 秒到分钟级 |
| 审计追踪 | 依赖人工记录 | Git 历史自动记录 |
| 协作 | 口头传达、截图 | Code Review、PR 流程 |
| 回滚 | 几乎不可能 | git revert 一键回滚 |
| Dim | Manual ops | IaC |
|---|---|---|
| Op | Click console | Viết code |
| Reproducibility | Dựa doc + memory | Code = doc, 100% reproducible |
| Change tracking | Không record / không đủ | Git version, full history |
| Collaboration | Verbal, doc pass | PR review |
| Rollback | Manual reverse | git revert + re-apply |
| Consistency | Env diff lớn | Dev/staging/prod identical |
Declarative vs Imperative
- Declarative: mô tả "tôi muốn gì", tool tự "làm thế nào". Terraform, CloudFormation. Idempotency tốt, flexibility hạn chế.
- Imperative: mô tả "làm thế nào", step-by-step. Ansible, shell script. Flexible, khó đảm bảo idempotency.
- Hybrid: Pulumi, AWS CDK viết bằng programming language thường, vừa declarative state vừa imperative flexibility.
2. Terraform workflow: Write → Plan → Apply
Terraform = tool IaC phổ biến nhất, HashiCorp dev. Workflow rõ ràng, 4 phase như "code → review → deploy → cleanup".
用声明式语言(HCL)描述你期望的基础设施状态。代码就是文档,可以提交到 Git 进行版本管理和 Code Review。
4-stage workflow
- Write: HCL (HashiCorp Configuration Language) define infra (.tf). Declare resource: server, DB, network.
- Plan:
terraform plancompare current vs target state, gen "execution plan" — báo bạn sẽ create/modify/delete resource nào. Safety net. - Apply: confirm plan OK →
terraform apply. Save state vào terraform.tfstate. - Destroy: không cần nữa →
terraform destroyclean hết, tránh cost.
| Command | Use | Modify infra | When |
|---|---|---|---|
terraform init | Init project, download Provider | No | First time hoặc add Provider |
terraform plan | Preview change | No | Every change trước |
terraform apply | Execute change | Yes | Sau confirm plan |
terraform destroy | Destroy mọi resource | Yes | Clean test env, decommission |
terraform state | Manage state file | Theo op | State migration, import |
3. Tool comparison
| 特性 | Terraform | CloudFormation |
|---|---|---|
| 厂商 | HashiCorp | AWS |
| 配置语言 | HCL | YAML / JSON |
| 声明式/命令式 | 声明式 | 声明式 |
| 多云支持 | 原生多云 | 仅 AWS |
| 状态管理 | State 文件 | AWS 托管 |
| 学习曲线 | 中等 | 中等偏高 |
| 社区生态 | 非常活跃 | AWS 生态 |
| 最佳场景 | 多云/混合云 | 纯 AWS 环境 |
| Tool | Language | Cloud support | Learning | Use |
|---|---|---|---|---|
| Terraform | HCL | Multi-cloud | Trung | Multi-cloud, team |
| Pulumi | Python/TS/Go | Multi-cloud | Thấp (dùng programming lang) | Dev-friendly, complex logic |
| AWS CloudFormation | JSON/YAML | AWS only | Trung | Pure AWS |
| AWS CDK | Python/TS/Java | AWS only | Thấp | AWS + programming lang |
| Ansible | YAML | Multi-cloud + bare metal | Thấp | Config management, hybrid |
Chọn?
- Startup / single-cloud: CloudFormation (AWS) hoặc native cloud tool
- Multi-cloud / mid-large team: Terraform, community lớn nhất, Provider phong phú, hire dễ
- Dev-led team: Pulumi / CDK, viết infra bằng lang quen, IDE tốt
- Config management: Ansible, mạnh ở internal server config (install software, modify file)
4. Config drift: bomb nổ chậm
Config drift = enemy silent nhất IaC. Actual infra state với code definition dần lệch.
Sao? Có ai "quick fix" prod issue, login console sửa SG thẳng; có ai debug tạm tăng config server quên đổi lại. "Tweaks" tích lũy = code + actual env lệch nặng.
团队使用 Terraform 部署了 3 台 Web 服务器,配置完全一致:Nginx 1.24、端口 443、2GB 内存。代码和实际状态完美匹配。
Hại config drift
- Không reproducible: code mô tả env ≠ actual, tạo env mới sẽ issue
- Rollback fail: tưởng rollback OK, nhưng env đã modify manual
- Security risk: port mở manual, permission relax bị quên → entry attack
- Audit fail: compliance audit dựa code, nhưng code không reflect actual
| Prevention | Note |
|---|---|
| Cấm manual change | IAM policy hạn chế console op |
| Drift detection định kỳ | Cron terraform plan check diff |
| Auto-fix | Detect drift → auto apply restore |
| Change audit | Bật CloudTrail audit log |
5. Best practices
# 忽略本地状态文件
*.tfstate
*.tfstate.backup
.terraform/
# 忽略敏感变量文件
*.tfvars
!example.tfvars6 core practices
- Modularize: trừu tượng reusable infra thành module (VPC, DB module), tránh copy-paste. Như function: define 1 chỗ, call nhiều.
- Env isolation: dev/staging/prod dùng state file + var file riêng, qua workspace hoặc directory.
- Remote state: state (tfstate) lưu remote backend (S3 + DynamoDB), support team collab + state lock, tránh concurrent conflict.
- Secret management: password, key đừng viết code, dùng Vault, AWS Secrets Manager.
- CI/CD:
terraform planvào PR flow,applyqua pipeline tự động, no manual local. - Code review: infra change cần Code Review như app code, đặc biệt SG + IAM policy.
Tổng kết
IaC = foundation modern cloud-native ops. Biến "manual op không describable" thành "code version-controlled", infra management từ "art" → "engineering".
- IaC essence: declarative code define desired infra, tool tự implement
- Terraform: Write → Plan → Apply, Plan = safety net
- Tool: multi-cloud → Terraform, single-cloud → native, dev team → Pulumi
- Drift: risk ẩn, process + tool double protect
- Engineering: modularize + env isolation + remote state + CI/CD
2026 cho VN dev
- Modern tooling 2026:
- Terraform: vẫn dominant
- OpenTofu: open-source fork of Terraform (after BSL license)
- Pulumi: lên mạnh cho TypeScript/Python team
- Crossplane: K8s-native IaC
- VN context:
- VN startup → Terraform + AWS/GCP
- VN bank → on-prem VMware + Ansible
- VN enterprise → Terraform + private cloud
- GitOps trend: ArgoCD, FluxCD đẩy IaC sang next level
- AI-era IaC: LLM gen Terraform/HCL từ natural language (Pulumi AI, Terramate AI)