DevOps & Infrastructure

Infrastructure as Code 2026: Terraform vs Pulumi vs Ansible vs CDK — Hướng Dẫn Chi Tiết Từ Zero Đến Production

So sánh toàn diện 4 công cụ IaC hot nhất hiện nay. Kiến trúc, code examples, case study thực tế, và lộ trình học cho DevOps Engineer muốn làm chủ infrastructure hiện đại.

30/06/2026 25 phút đọc Võ Đào Huy Hoàng

1. Giới thiệu & Vấn đề

Năm 2010, một DevOps engineer cần tạo 50 VMs cho hệ thống production — họ login vào AWS Console, click từng menu, tạo từng instance thủ công. Nếu cần thay đổi cấu hình cho tất cả? Click lại từng cái một. Nếu muốn replicate môi trường staging giống production? Copy-paste thủ công và cầu nguyện. 😅

Năm 2026, câu chuyện đã hoàn toàn khác. Với Infrastructure as Code (IaC), toàn bộ hạ tầng — từ VPC, load balancer, database cluster, đến Kubernetes nodes — được định nghĩa trong code. Bạn git push → pipeline chạy → infrastructure được tạo/thay đổi tự động trong vài phút. 🚀

92% Teams DevOps dùng IaC (2026)
70% Giảm provisioning time
85% Giảm human errors
$4.2B IaC market size 2026

Nhưng thị trường IaC có hàng chục công cụ: Terraform, Pulumi, Ansible, CDK, OpenTofu, Crossplane, Packer, Chef, SaltStack... Trong bài viết này, chúng ta sẽ đi sâu vào 4 công cụ phổ biến nhất, so sánh từng khía cạnh, và giúp bạn ra quyết định đúng đắn cho dự án.

2. Tổng quan Infrastructure as Code

Infrastructure as Code (IaC) là practice quản lý và cung cấp hạ tầng (infrastructure) thông qua file code định nghĩa, thay vì cấu hình thủ công hoặc sử dụng công cụ GUI. IaC biến infra thành software — version controlled, testable, reviewable, reproducible.

3 Nguyên tắc cốt lõi của IaC

  • 🔍 Declarative vs Imperative — Declarative: bạn mô tả trạng thái "muốn gì" (Terraform, CloudFormation). Imperative: bạn viết "làm thế nào" từng bước (Pulumi, CDK)
  • 🔄 State Management — Hệ thống cần theo dõi trạng thái thực tế vs trạng thái mong muốn. Terraform dùng Terraform State file, Ansible stateless, Pulumi dùng Pulumi Cloud
  • 🔁 Idempotency — Chạy cùng code 100 lần → kết quả phải giống nhau. Đây là property quan trọng nhất của IaC tool
🔥 Phân loại IaC tools:
  • Cloud Provisioning (Terraform, Pulumi, CDK) — tạo VMs, networks, databases, load balancers
  • Configuration Management (Ansible, Chef, SaltStack) — cấu hình software, packages, services trên existing servers
  • Image Building (Packer) — tạo custom VM images (AMIs, Docker images)

Trong thực tế, nhiều team kết hợp 2-3 tools: Terraform provisioning + Ansible configures + Packer builds images.

3. Terraform — Ngôi vương IaC 🔱

Terraform (HashiCorp, 2014) là công cụ IaC phổ biến nhất thế giới hiện tại. Với hơn 42,000+ GitHub stars, hệ sinh thái 3,000+ providers hỗ trợ mọi cloud (AWS, Azure, GCP, Alibaba Cloud, Cloudflare, Kubernetes, GitHub...), Terraform là lựa chọn mặc định cho phần lớn teams DevOps.

42K+ GitHub Stars ⭐
3,000+ Providers
70% IaC market share
1M+ Active practitioners

Kiến trúc & Providers

Terraform hoạt động theo mô hình declarative — bạn viết file HCL (HashiCorp Configuration Language) mô tả trạng thái mong muốn, Terraform tự động tính toán và thực thi các bước để đạt trạng thái đó.

📝
.tf Files
🔄
Terraform Core
☁️
Providers
🏗️
Cloud Resources

Luồng hoạt động:

  1. 🧑‍💻 Dev viết .tf files định nghĩa infra
  2. 📋 terraform plan — so sánh desired state vs current state → tạo execution plan
  3. 🚀 terraform apply — thực thi plan, tạo/thay đổi resources qua cloud APIs
  4. 💾 State file (terraform.tfstate) lưu mapping giữa code và real resources
⚠️ Terraform License Change (2023): HashiCorp chuyển Terraform sang license BSL (Business Source License). Điều này dẫn đến sự ra đời của OpenTofu — fork mã nguồn mở từ Terraform, được Linux Foundation bảo trợ. Chi tiết trong phần Xu hướng 2026.

Code example thực tế

Ví dụ: triển khai toàn bộ infrastructure cho 1 web app trên AWS — VPC, ECS cluster, RDS, CloudFront CDN:

# main.tf — AWS ECS Fargate Stack terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } backend "s3" { bucket = "mycompany-tfstate" key = "prod/terraform.tfstate" region = "ap-southeast-1" dynamodb_table = "terraform-lock" } } # VPC resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" enable_dns_hostnames = true tags = { Name = "prod-vpc" } } # ECS Cluster resource "aws_ecs_cluster" "app" { name = "prod-cluster" setting { name = "containerInsights" value = "enabled" } } # RDS PostgreSQL resource "aws_db_instance" "db" { identifier = "prod-db" engine = "postgres" engine_version = "16.1" instance_class = "db.r6g.large" allocated_storage = 100 multi_az = true backup_retention_period = 7 }
# Command workflow terraform init # Download providers, setup backend terraform plan # Preview changes (dry-run) terraform apply # Apply changes to AWS terraform destroy # Tear down everything
💡 Điểm mạnh Terraform: HCL dễ đọc, planner preview trước khi apply, module system tái sử dụng, state management chặt chẽ, ecosystem provider lớn nhất. Ideal cho multi-cloud provisioning.

4. Pulumi — IaC Bằng Code Thực Thụ 🐍

Pulumi (2017) là thế hệ mới của IaC — thay vì học một DSL mới (như HCL), bạn dùng ngôn ngữ lập trình thực thụ (Python, TypeScript, Go, C#, Java) để định nghĩa infrastructure. Pulumi có thể làm mọi thứ Terraform làm, nhưng với sức mạnh của language thực thụ: loops, functions, classes, type checking, IDE autocomplete, unit testing.

🐍
Python / TS / Go
⚙️
Pulumi Engine
☁️
Cloud SDKs
🏗️
Resources

Code bằng Python & TypeScript

Ví dụ cùng infrastructure như Terraform trên, nhưng dùng Python:

# __main__.py — Pulumi Python import pulumi import pulumi_aws as aws # VPC vpc = aws.ec2.Vpc("prod-vpc", cidr_block="10.0.0.0/16", enable_dns_hostnames=True, tags={"Name": "prod-vpc"} ) # ECS Cluster cluster = aws.ecs.Cluster("prod-cluster", settings=[{ "name": "containerInsights", "value": "enabled" }] ) # RDS — với logic phức tạp bằng Python! db = aws.rds.Instance("prod-db", engine="postgres", engine_version="16.1", instance_class="db.r6g.large", allocated_storage=100, multi_az=True, backup_retention_period=7 ) # Output URL pulumi.export("db_endpoint", db.endpoint)

Tại sao Pulumi với Python mạnh hơn HCL?

  • 🔁 Loops & Functions — tạo N subnets bằng list comprehension, không cần count hacky
  • 🧪 Unit Testing — test infra bằng pytest/unittest, mock cloud APIs
  • 📦 Package Ecosystem — dùng pip install thêm logic, không phải write custom provider
  • 🤖 AI Integration — LLM (GPT-4, Claude) code Python tốt hơn HCL rất nhiều → AI-assisted IaC becomes real
⚠️ Trade-off: Pulumi yêu cầu Pulumi Cloud (hoặc self-hosted backend) để manage state. Free tier đủ cho cá nhân devs, nhưng enterprise cần license. Terraform dùng S3/GCS backend miễn phí.

5. Ansible — Configuration Management King 👑

Ansible (Red Hat, 2012) khác biệt hoàn toàn với Terraform/Pulumi. Trong khi Terraform/Pulumi tạo infrastructure (VMs, networks, databases), Ansible cấu hình servers — cài đặt software, config services, deploy applications trên existing infrastructure.

Ansible hoạt động theo mô hình agentless — không cần cài agent trên target servers. Nó kết nối qua SSH (hoặc WinRM), đẩy modules nhỏ chạy trên server rồi xóa. Đơn giản, an toàn, dễ audit.

Tại sao Ansible vẫn quan trọng trong era IaC?

🔥 Terraform tạo "xương", Ansible "thịt":
  • 🔧 Terraform tạo VM → Ansible cài Docker, config Nginx, deploy app
  • 🔧 Pulumi tạo EKS cluster → Ansible bootstrap worker nodes
  • 🔧 CDK tạo RDS instance → Ansible setup database schemas, seed data

Nhiều production teams dùng combo: Terraform + Ansible hoặc Pulumi + Ansible. Terraform quản lý lifecycle của cloud resources, Ansible quản lý state của software trên servers.

Code example — Ansible Playbook

# deploy-app.yml — Deploy Node.js app lên EC2 - hosts: web_servers become: yes vars: app_version: "2.4.1" node_port: 3000 tasks: - name: Install Docker apt: name: docker.io state: present update_cache: yes - name: Pull app image docker_image: name: "myapp/api:{{ app_version }}" source: pull - name: Run container docker_container: name: myapp-api image: "myapp/api:{{ app_version }}" state: started restart_policy: unless-stopped ports: - "{{ node_port }}:3000" env: DATABASE_URL: "{{ vault_db_url }}" - name: Configure Nginx reverse proxy template: src: nginx.conf.j2 dest: /etc/nginx/sites-available/myapp notify: Reload Nginx
# Deploy ansible-playbook -i inventory/prod deploy-app.yml --diff # Dry-run (check mode) ansible-playbook -i inventory/prod deploy-app.yml --check --diff

Ansible vs Terraform — Không phải đối thủ

Khía cạnh Ansible Terraform
Mục đích Configure servers, deploy apps Provision cloud resources
Model Agentless (SSH), push-based API-driven, pull state
Language YAML (Playbooks) / Python (Modules) HCL (Terraform) / Python (Pulumi)
State Stateless (idempotent by design) Stateful (tfstate file)
Best for Configuration, provisioning, deployment Infrastructure provisioning
Cloud support Via modules (slower) Native providers (faster)
Combo 🤝 Dùng CÙNG Terraform/Pulumi 🤝 Dùng CÙNG Ansible
💡 Best practice 2026: Dùng Terraform/Pulumi để tạo VMs + networks. Dùng Ansible để config servers + deploy apps. Hai tool bổ trợ nhau, không thay thế nhau.

6. AWS CDK — IaC Kiểu Developer 🧑‍💻

AWS Cloud Development Kit (CDK) là framework IaC của AWS — cho phép bạn viết infrastructure bằng ngôn ngữ quen thuộc (TypeScript, Python, Go, Java, C#) và CDK tự động chuyển thành CloudFormation templates. CDK kết hợp sức mạnh của programming language thực thụ với sự ổn định của CloudFormation backend.

💻
TS / Python / Go
📦
CDK Constructs
📋
CloudFormation
☁️
AWS Resources

CDK Code Example — TypeScript

// lib/ecs-stack.ts — AWS CDK TypeScript import * as cdk from 'aws-cdk-lib'; import * as ecs from 'aws-cdk-lib/aws-ecs'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import * as rds from 'aws-cdk-lib/aws-rds'; export class EcsStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // VPC — 1 dòng thay vì 50 dòng Terraform const vpc = new ec2.Vpc(this, 'ProdVPC', { maxAzs: 3, natGateways: 2, }); // ECS Cluster const cluster = new ecs.Cluster(this, 'ProdCluster', { vpc, containerInsights: true, }); // Fargate Service — high-level construct const service = new ecs_patterns.ApplicationLoadBalancedFargateService( this, 'WebService', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('myapp/api:latest'), containerPort: 3000, }, desiredCount: 3, publicLoadBalancer: true, } ); } }
# CDK workflow cdk init app --language typescript cdk synth # Generate CloudFormation template cdk diff # Preview changes cdk deploy # Deploy to AWS
⚠️ Hạn chế CDK: Chỉ hoạt động trên AWS (multi-cloud = không thể). CloudFormation backend có rate limits và timeout (60 phút/resource). CDK v2 đã consolidate tất cả constructs vào aws-cdk-lib, đơn giản hơn CDK v1 nhiều.
💡 CDK khi nào hợp lý: Team 100% AWS, đã quen TypeScript/Python, muốn abstraction cao (L2/L3 constructs). CDK constructs có thể share qua npm/pip như code library bình thường.

7. So Sánh Chi Tiết 🔍

Bảng so sánh 4 công cụ

Tính năng Terraform Pulumi Ansible CDK
Language HCL (declarative) Python/TS/Go (imperative) YAML + Jinja2 TS/Python/Go (imperative)
Cloud support 🌐 Multi-cloud (3000+ providers) 🌐 Multi-cloud 🌐 Multi-cloud (via modules) ☁️ AWS only
Learning curve 🟢 Trung bình (học HCL) 🟢 Thấp (dùng ngôn ngữ quen) 🟢 Thấp (YAML đơn giản) 🟡 Trung bình
State management Terraform State (S3/GCS) Pulumi Cloud / self-hosted Stateless CloudFormation state
Unit testing terratest (Go) ✅ pytest/unittest (native) molecule (Python) assertions (CDK assert)
AI/LLM integration 🟡 Moderate (HCL) 🟢 Excellent (Python/TS) 🟡 Moderate (YAML) 🟢 Good (TS/Python)
Provisioning ✅ Strong ✅ Strong ❌ Weak (slow) ✅ Strong (AWS)
Config Management ❌ Not designed for ❌ Not designed for ✅ Excellent ❌ Not designed for
Community/Ecosystem 🔥 Largest 📈 Growing fast 🔥 Mature ☁️ AWS-centric
License (2026) ⚠️ BSL (OpenTofu fork) Apache 2.0 (open source) ✅ GPL v3 ✅ Apache 2.0
Enterprise adoption 🔥 70%+ market share 📈 15%+ growing 🔥 Standard for config ☁️ 25%+ on AWS

Khi nào chọn cái nào? 🤔

✅ Chọn Terraform khi:
  • Multi-cloud hoặc hybrid cloud deployment
  • Team lớn, cần standardize IaC across organization
  • Market share lớn → dễ tuyển dụng, nhiều resources học
  • Module ecosystem phong phú — không phải build from scratch
  • Hợp lý nhất: Multi-cloud + team 10-50+ engineers
✅ Chọn Pulumi khi:
  • Team developer-centric, quen Python/TypeScript hơn HCL
  • Cần logic phức tạp trong infra (loops, conditions, abstractions)
  • Đang bắt đầu từ zero — AI assist với Python/TS tốt hơn HCL
  • Cần unit testing cho infrastructure
  • Hợp lý nhất: Dev team muốn tự quản lý infra bằng code quen thuộc
✅ Chọn Ansible khi:
  • Cần config management trên existing servers
  • Deploy applications, setup software stacks
  • Kết hợp với Terraform/Pulumi (infrastructure → configuration)
  • Team operations / sysadmin-centric
  • Hợp lý nhất: Configuration management + deployment automation
✅ Chọn CDK khi:
  • Team 100% AWS, không có plan multi-cloud
  • Developer muốn high-level abstractions (L2/L3 constructs)
  • Đã có CloudFormation experience, muốn upgrade
  • CDK constructs shareable như npm packages
  • Hợp lý nhất: AWS-first startup, developer team
🎯 Combo phổ biến nhất 2026:
  • Terraform + Ansible — "Industry standard" combo (60%+ teams)
  • Pulumi + Ansible — "Developer-friendly" combo (growing fast)
  • CDK + SSM — "AWS-native" combo (no Ansible needed)
  • OpenTofu + Ansible — "Open source pure" combo (emerging)

8. Case Study Thực Tế 🏢

Case 1: Startup SaaS — Pulumi từ zero

Công ty: Startup SaaS Việt Nam, team 5 developers, product: AI-powered analytics platform
Yêu cầu: Deploy trên AWS, 20 microservices, CI/CD tự động, launch trong 3 tháng
Stack: Pulumi (TypeScript) + GitHub Actions + ECS Fargate

Team quyết định dùng Pulumi + TypeScript thay vì Terraform vì: developers biết TypeScript tốt hơn HCL, muốn dùng loops/functions để manage 20 services không cần copy-paste, và muốn AI assist (GPT-4 code TypeScript giỏi hơn HCL).

// Pulumi — Tạo ECS service cho 20 microservices bằng loop const services = ['api-gateway', 'auth', 'analytics', 'billing', ...]; services.map(name => new EcsService(name, { cluster, image: `myapp/${name}:latest`, cpu: 256, memory: 512, })); // 15 lines thay vì 15 × 40 = 600 lines Terraform!

Kết quả: MVP production-ready trong 2.5 tháng. CI/CD pipeline 20 services = 1 Pulumi program. Chi phí infra: $350/tháng (ECS Fargate). Dev time tiết kiệm 40% so với Terraform estimate.

Case 2: Enterprise Bank — Terraform + Ansible multi-cloud

Công ty: Ngân hàng lớn tại Việt Nam, 50+ engineers infrastructure
Yêu cầu: Multi-cloud (AWS + on-premise OpenStack), compliance SOC2, audit trail cho mọi thay đổi
Stack: Terraform (provisioning) + Ansible (configuration) + Terragrunt (wrapper)

📝
Terraform Modules
🔄
Terragrunt
☁️
AWS + OpenStack
🔧
Ansible Config

Module structure: modules/vpc/, modules/ecs/, modules/rds/ — mỗi module 200-400 dòng HCL, được reuse across 15 environments (dev, staging, prod × 5 regions). Terragrunt wrap Terraform để manage state separation và dependency ordering.

Kết quả: 15 environments managed bằng 1 codebase. Compliance audit: mỗi thay đổi traceable qua Git history + Terraform plan output. DevOps team giảm từ 8 người (manual ops) xuống 3 người (IaC pipeline). 200+ deployments/tháng, zero human error.

Case 3: E-commerce Scale — CDK + Terraform hybrid

Công ty: E-commerce platform, 100% AWS, 30+ engineers
Yêu cầu: 500+ Lambda functions, API Gateway, DynamoDB, EventBridge
Stack: CDK (serverless constructs) + Terraform (VPC, RDS, shared infra)

Dùng CDK cho serverless (Lambda, API Gateway, DynamoDB) vì CDK L3 constructs giúp deploy entire API chỉ với 50 lines code. Dùng Terraform cho shared infra (VPC, RDS, ElastiCache) vì team cần multi-AZ setup phức tạp mà CDK CloudFormation backend handle chậm.

📊 Bài học từ 3 cases: Không có "best tool" — mỗi case có optimal stack. Startup → Pulumi (developer speed). Enterprise → Terraform + Ansible (standardization + compliance). Serverless → CDK (abstraction power). Chọn tool phù hợp bài toán, không chạy theo trend.

10. Lộ Trình Học IaC 📚

Nếu bạn mới bắt đầu, đây là lộ trình tối ưu từ zero đến production-ready:

  1. 📅 Tuần 1-2: Terraform căn bản
    Học HCL syntax, init/plan/apply/destroy, providers, resources, variables, outputs.
    Mục tiêu: deploy được 1 EC2 + VPC trên AWS bằng Terraform.
  2. 📅 Tuần 3-4: Terraform nâng cao
    Học modules, state management (S3 backend), workspaces, provisioners.
    Mục tiêu: build reusable module library cho team.
  3. 📅 Tuần 5-6: Ansible căn bản
    Học inventory, playbooks, roles, modules.
    Mục tiêu: configure server + deploy app bằng Ansible.
  4. 📅 Tuần 7-8: Combo Terraform + Ansible
    Terraform tạo infra → Ansible configure servers → CI/CD pipeline.
    Mục tiêu: full deployment pipeline tự động.
  5. 📅 Tuần 9-10: Pulumi/CDK (optional)
    Thử Pulumi (Python) hoặc CDK (TypeScript) để so sánh.
    Mục tiêu: decide tool phù hợp nhất cho team/project.
🎯 Tổng thời gian: ~10 tuần từ zero đến production-ready IaC stack. Nếu chỉ cần Terraform + Ansible: 8 tuần. Bắt đầu với Terraform vì ecosystem lớn nhất, sau đó expand sang tools khác khi cần.

💻 Code Example: Terraform Infrastructure

# Terraform AWS Infrastructure
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
  tags = { Name = "production-vpc" }
}

resource "aws_ecs_cluster" "app" {
  name = "app-cluster"
}

11. Kết Luận 🎯

Infrastructure as Code không còn là optional — nó là tiêu chuẩn bắt buộc cho bất kỳ team DevOps nào năm 2026. 4 công cụ chính đều có strengths riêng:

  • 🔱 Terraform: Ngôi vương multi-cloud, ecosystem lớn nhất, phù hợp enterprise → nhưng license BSL đang đe dọa
  • 🐍 Pulumi: Thế hệ mới, code thực thụ, AI-friendly, testing native → đang grow nhanh nhất
  • 👑 Ansible: Configuration management king, agentless, đơn giản → best friend của Terraform/Pulumi
  • 🧑‍💻 CDK: AWS-native, developer-friendly, high-level abstractions → nếu 100% AWS thì rất mạnh

Khuyến nghị thực tế: Nếu bạn vừa bắt đầu, hãy học Terraform + Ansible trước — combo này cover 80% use cases, ecosystem lớn nhất, dễ tuyển dụng nhất. Sau đó, nếu team developer-centric và muốn modern stack, hãy evaluate Pulumi. Nếu 100% AWS, CDK là lựa chọn xuất sắc.

Xu hướng lớn nhất 2026: AI-assisted IaC sẽ thay đổi cách chúng ta viết infrastructure code. Engineer chuyển từ "viết code" sang "review + specify". OpenTofu sẽ tiếp tục grow thách thức Terraform. Platform Engineering sẽ abstract away IaC complexity cho developers.

Dù bạn chọn tool nào, hãy nhớ nguyên tắc vàng: Infra là code → version control nó, test nó, review nó, treat nó như production code. 🚀