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:

  1. Read config: Đọc tất cả .tf files trong working directory.
  2. Refresh state: So sánh state hiện tại với state mong muốn.
  3. Plan: Tính toán execution plan — tạo, thay đổi, hoặc xóa resources nào.
  4. Apply: Thực thi plan, gọi API của cloud provider để tạo/thay đổi resources.
  5. 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ệmMô tảVí dụ
ProviderPlugin giao tiếp với cloud/APIaws, azurerm, google, proxmox
ResourceThực thể hạ tầng được quản lýaws_instance, aws_s3_bucket
Data SourceĐọc dữ liệu từ infrastructuredata.aws_ami, data.aws_vpc
VariableTham số đầu vào có thể tái sử dụngvariable “region” {}
OutputGiá trị xuất ra sau applyoutput “instance_ip” {}
ModuleGói tái sử dụng nhiều resourcesmodule “vpc” { source = “./vpc” }
StateFile theo dõi infrastructure hiện tạiterraform.tfstate
BackendNơi lưu state filelocal, 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ạnhPhù hợp
TerraformHCL100+ providersMulti-cloud, declarative, cộng đồng lớnProvisioning infrastructure
AnsibleYAMLMulti-cloud + on-premAgentless, dễ học, idempotentConfiguration management
PulumiPython/JS/GoMulti-cloudDùng ngôn ngữ lập trình thậtTeam có kỹ năng coding
CloudFormationJSON/YAMLAWS onlyTích hợp sâu AWS100% 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.tfstate trê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 plan trong PR review, terraform apply sau khi merge. Không chạy apply trực tiếp trên local.
  • Không commit state file: Thêm terraform.tfstate vào .gitignore. State chứa sensitive data (IPs, passwords).
  • Dùng variables: Hardcode values vào resource blocks là anti-pattern. Dùng variables.tfterraform.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 kubernetes quản lý K8s resources (deployments, services, configmaps). Provider helm deploy Helm charts. Provider kubectl apply 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 DockerProxmox Backup Server trên vnhte.com.

Chào các bạn mình là Quốc Hùng , mình sinh ra thuộc cung song tử ,song tử luôn khẳng định chính mình ,luôn luôn phấn đấu vượt lên phía trước ,mình sinh ra và lớn lên tại vùng đất võ cổ truyền ,đam mê của mình là coder ,ngày đi học tối về viết blog ...