Skip to content

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ươngNội dung
1IaC concept
2Terraform workflow
3Tool comparison
4Config drift
5Best 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.

交互演示 ── 手动运维 vs 基础设施即代码
手动运维流程
1
🌐
登录云控制台
需要记住密码
2
🖥️
手动创建服务器
配置可能遗漏
3
🔧
配置安全组规则
容易开放过多端口
4
💾
挂载存储卷
大小可能选错
5
🔗
配置负载均衡
路由规则易出错
6
📋
手动记录到文档
文档很快过时
对比维度手动运维基础设施即代码
可重复性每次操作可能不同代码保证完全一致
速度分钟到小时级秒到分钟级
审计追踪依赖人工记录Git 历史自动记录
协作口头传达、截图Code Review、PR 流程
回滚几乎不可能git revert 一键回滚
DimManual opsIaC
OpClick consoleViết code
ReproducibilityDựa doc + memoryCode = doc, 100% reproducible
Change trackingKhông record / không đủGit version, full history
CollaborationVerbal, doc passPR review
RollbackManual reversegit revert + re-apply
ConsistencyEnv diff lớnDev/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".

交互演示 ── Terraform 工作流四阶段
📝Write
🔍Plan
🚀Apply
🗑️Destroy
📝Write ── 编写基础设施代码

用声明式语言(HCL)描述你期望的基础设施状态。代码就是文档,可以提交到 Git 进行版本管理和 Code Review。

Terminal
📄使用 .tf 文件描述资源
🔧HCL 语法简洁易读
📦支持模块化复用

4-stage workflow

  1. Write: HCL (HashiCorp Configuration Language) define infra (.tf). Declare resource: server, DB, network.
  2. Plan: terraform plan compare current vs target state, gen "execution plan" — báo bạn sẽ create/modify/delete resource nào. Safety net.
  3. Apply: confirm plan OK → terraform apply. Save state vào terraform.tfstate.
  4. Destroy: không cần nữa → terraform destroy clean hết, tránh cost.
CommandUseModify infraWhen
terraform initInit project, download ProviderNoFirst time hoặc add Provider
terraform planPreview changeNoEvery change trước
terraform applyExecute changeYesSau confirm plan
terraform destroyDestroy mọi resourceYesClean test env, decommission
terraform stateManage state fileTheo opState migration, import

3. Tool comparison

交互演示 ── 主流 IaC 工具对比
选择要对比的工具(至少选 2 个):
特性🟣Terraform🟠CloudFormation
厂商HashiCorpAWS
配置语言HCLYAML / JSON
声明式/命令式声明式声明式
多云支持原生多云仅 AWS
状态管理State 文件AWS 托管
学习曲线中等中等偏高
社区生态非常活跃AWS 生态
最佳场景多云/混合云纯 AWS 环境
点击下方工具名称查看详细介绍和代码示例
ToolLanguageCloud supportLearningUse
TerraformHCLMulti-cloudTrungMulti-cloud, team
PulumiPython/TS/GoMulti-cloudThấp (dùng programming lang)Dev-friendly, complex logic
AWS CloudFormationJSON/YAMLAWS onlyTrungPure AWS
AWS CDKPython/TS/JavaAWS onlyThấpAWS + programming lang
AnsibleYAMLMulti-cloud + bare metalThấpConfig 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.

交互演示 ── 配置漂移:无声的定时炸弹
初始部署
手动修改
又一次修改
漂移加剧
IaC 检测
期望状态(代码定义)
🖥️
Server-A
Nginx 1.24 | 443 | 2GB
🖥️
Server-B
Nginx 1.24 | 443 | 2GB
🖥️
Server-C
Nginx 1.24 | 443 | 2GB
状态一致
实际状态(线上环境)
🖥️
Server-A
Nginx 1.24 | 443 | 2GB
🖥️
Server-B
Nginx 1.24 | 443 | 2GB
🖥️
Server-C
Nginx 1.24 | 443 | 2GB
第 0 步:通过 IaC 初始部署

团队使用 Terraform 部署了 3 台 Web 服务器,配置完全一致:Nginx 1.24、端口 443、2GB 内存。代码和实际状态完美匹配。

关键教训
🚫禁止手动修改线上环境,所有变更必须通过代码
🔍定期运行 terraform plan 检测漂移
🔒限制生产环境的 SSH 权限,减少人为干预
📋建立变更审批流程(PR → Review → Merge → Apply)

Hại config drift

  1. Không reproducible: code mô tả env ≠ actual, tạo env mới sẽ issue
  2. Rollback fail: tưởng rollback OK, nhưng env đã modify manual
  3. Security risk: port mở manual, permission relax bị quên → entry attack
  4. Audit fail: compliance audit dựa code, nhưng code không reflect actual
PreventionNote
Cấm manual changeIAM policy hạn chế console op
Drift detection định kỳCron terraform plan check diff
Auto-fixDetect drift → auto apply restore
Change auditBật CloudTrail audit log

5. Best practices

交互演示 ── IaC 最佳实践
📂
实践一:基础设施代码纳入版本控制
像管理应用代码一样管理基础设施代码
✅ 推荐做法
所有 .tf 文件提交到 Git 仓库
使用分支策略(main / dev / feature)
通过 Pull Request 进行代码审查
在 CI 中自动运行 terraform plan
❌ 反面模式
在本地执行 apply 后不提交代码
直接在 main 分支上修改
将 .tfstate 文件提交到 Git
跳过 Code Review 直接部署
.gitignore 示例
# 忽略本地状态文件
*.tfstate
*.tfstate.backup
.terraform/

# 忽略敏感变量文件
*.tfvars
!example.tfvars
实践成熟度
入门
基础
进阶
成熟
卓越

6 core practices

  1. 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.
  2. Env isolation: dev/staging/prod dùng state file + var file riêng, qua workspace hoặc directory.
  3. Remote state: state (tfstate) lưu remote backend (S3 + DynamoDB), support team collab + state lock, tránh concurrent conflict.
  4. Secret management: password, key đừng viết code, dùng Vault, AWS Secrets Manager.
  5. CI/CD: terraform plan vào PR flow, apply qua pipeline tự động, no manual local.
  6. 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".

  1. IaC essence: declarative code define desired infra, tool tự implement
  2. Terraform: Write → Plan → Apply, Plan = safety net
  3. Tool: multi-cloud → Terraform, single-cloud → native, dev team → Pulumi
  4. Drift: risk ẩn, process + tool double protect
  5. 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)

Tài liệu