Terraform là gì? Terraform là công cụ Infrastructure as Code (IaC) mã nguồn mở do HashiCorp phát triển, cho phép bạn định nghĩa và quản lý hạ tầng IT bằng code thay vì thao tác thủ công. Với Terraform, bạn viết file cấu hình bằng ngôn ngữ HCL (HashiCorp Configuration Language), Terraform sẽ tự động tạo, thay đổi và xóa resources trên bất kỳ cloud provider nào — AWS, Azure, GCP, hay on-premise.
Trong bài viết này, mình sẽ giải thích chi tiết Terraform là gì, cách hoạt động, so sánh với các công cụ IaC khác (Ansible, Pulumi, CloudFormation), hướng dẫn cài đặt và viết file cấu hình đầu tiên, cùng best practices khi dùng Terraform trong production.
Terraform là gì và tại sao nên dùng?
Infrastructure as Code (IaC) là phương pháp quản lý hạ tầng IT (servers, networks, databases, load balancers…) bằng file cấu hình có thể version control, thay vì cấu hình thủ công qua UI hoặc CLI. Terraform là một trong những công cụ IaC phổ biến nhất hiện nay với hơn 3,000 providers và được sử dụng bởi hàng triệu developer.
- Declarative: Bạn mô tả kết quả cuối cùng (desired state), Terraform tự tìm cách đạt được — không cần viết script từng bước.
- Multi-cloud: Hỗ trợ 100+ providers: AWS, Azure, GCP, VMware, Proxmox, Kubernetes, GitHub, Docker…
- Idempotent: Chạy nhiều lần cùng kết quả. Nếu infrastructure đã đúng state, Terraform không thay đổi gì.
- State management: Terraform theo dõi state của infrastructure, chỉ áp dụng delta (thay đổi) khi cần.
- Plan trước khi apply: Xem trước tất cả thay đổi trước khi thực hiện — giảm rủi ro sai sót.
Cách Terraform hoạt động
Workflow cơ bản của Terraform gồm 3 bước: Write → Plan → Apply.
# 1. Write: Viết file cấu hình (main.tf) # 2. Plan: Xem trước thay đổi terraform plan # 3. Apply: Áp dụng thay đổi terraform apply
Behind the scenes, Terraform hoạt động theo quy trình:
- Read config: Đọc tất cả
.tffiles trong working directory. - Refresh state: So sánh state hiện tại với state mong muốn.
- Plan: Tính toán execution plan — tạo, thay đổi, hoặc xóa resources nào.
- Apply: Thực thi plan, gọi API của cloud provider để tạo/thay đổi resources.
- Update state: Cập nhật state file phản ánh infrastructure mới.
Cài đặt Terraform
# macOS brew tap hashicorp/tap brew install hashicorp/tap/terraform # Ubuntu/Debian wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list sudo apt update && sudo apt install terraform # CentOS/RHEL sudo yum install -y yum-utils sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo sudo yum -y install terraform # Verify terraform version
Ví dụ Terraform đầu tiên
Tạo một file main.tf để provision một EC2 instance trên AWS:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-southeast-1"
}
resource "aws_instance" "example" {
ami = "ami-0c02fb55956c7d316"
instance_type = "t3.micro"
tags = {
Name = "terraform-example"
}
}
# Khởi tạo (download provider) terraform init # Xem trước thay đổi terraform plan # Áp dụng terraform apply # Xóa tất cả resources terraform destroy
Các khái niệm cốt lõi trong Terraform
| Khái niệm | Mô tả | Ví dụ |
|---|---|---|
| Provider | Plugin giao tiếp với cloud/API | aws, azurerm, google, proxmox |
| Resource | Thực thể hạ tầng được quản lý | aws_instance, aws_s3_bucket |
| Data Source | Đọc dữ liệu từ infrastructure | data.aws_ami, data.aws_vpc |
| Variable | Tham số đầu vào có thể tái sử dụng | variable “region” {} |
| Output | Giá trị xuất ra sau apply | output “instance_ip” {} |
| Module | Gói tái sử dụng nhiều resources | module “vpc” { source = “./vpc” } |
| State | File theo dõi infrastructure hiện tại | terraform.tfstate |
| Backend | Nơi lưu state file | local, S3, GCS, Terraform Cloud |
So sánh Terraform với các công cụ IaC khác
| Công cụ | Ngôn ngữ | Cloud Support | Điểm mạnh | Phù hợp |
|---|---|---|---|---|
| Terraform | HCL | 100+ providers | Multi-cloud, declarative, cộng đồng lớn | Provisioning infrastructure |
| Ansible | YAML | Multi-cloud + on-prem | Agentless, dễ học, idempotent | Configuration management |
| Pulumi | Python/JS/Go | Multi-cloud | Dùng ngôn ngữ lập trình thật | Team có kỹ năng coding |
| CloudFormation | JSON/YAML | AWS only | Tích hợp sâu AWS | 100% AWS stack |
Terraform vs Ansible: Terraform là declarative — bạn mô tả kết quả cuối, Terraform tự tìm cách đạt được. Ansible là imperative — bạn viết từng bước thực hiện. Terraform tốt cho provisioning infrastructure (tạo VM, VPC, database), Ansible tốt cho configuration management (cài software, cấu hình service). Nhiều team dùng cả hai kết hợp.
Best practices khi dùng Terraform
- Lưu state ở remote backend: Không bao giờ lưu
terraform.tfstatetrên local. Dùng Terraform Cloud (miễn phí cho team nhỏ), AWS S3 + DynamoDB, hoặc GCS. Đảm bảo state được encrypt và có state locking. - Dùng modules: Chia infrastructure thành modules tái sử dụng (VPC module, EC2 module, RDS module). Tránh duplicate code.
- Version pinning: Lock provider version và Terraform version để tránh breaking changes:
required_providers { aws = "~> 5.0" } - CI/CD pipeline: Chạy
terraform plantrong PR review,terraform applysau khi merge. Không chạy apply trực tiếp trên local. - Không commit state file: Thêm
terraform.tfstatevào.gitignore. State chứa sensitive data (IPs, passwords). - Dùng variables: Hardcode values vào resource blocks là anti-pattern. Dùng
variables.tfvàterraform.tfvars.
FAQ – Câu hỏi thường gặp về Terraform
- Terraform có miễn phí không? Terraform core là mã nguồn mở (BSL 1.1) và miễn phí. HashiCorp có Terraform Cloud/Enterprise với tính năng thêm: remote execution, policy enforcement, team management. Với dự án nhỏ, bản miễn phí là đủ.
- Làm sao tránh state conflict khi làm team? Dùng remote backend với state locking (S3 + DynamoDB hoặc Terraform Cloud). Khi một người đang apply, state bị lock cho đến khi hoàn tất.
- Có thể import infrastructure hiện có vào Terraform không? Có, dùng
terraform import <resource> <id>. Bạn cần viết resource block tương ứng trước, sau đó chạy import. Terraform sẽ map resource hiện có vào state. - Terraform quản lý Kubernetes được không? Có. Provider
kubernetesquản lý K8s resources (deployments, services, configmaps). Providerhelmdeploy Helm charts. Providerkubectlapply manifests YAML. - Nên lưu state ở đâu? Remote backend — Terraform Cloud (miễn phí), AWS S3 + DynamoDB, GCS, Azure Blob. Không bao giờ lưu local vì mất state = mất track infrastructure.
Tìm hiểu thêm về Docker toàn tập, so sánh LXC vs Docker và Proxmox Backup Server trên vnhte.com.