Danh sách bài viết trong series Hành Trình Làm Chủ Terraform
- Bài 1. Học Terraform Cơ Bản: Terraform Là Gì? Cài Đặt Và Viết Mã Đầu Tiên
- Bài 2. Học Terraform Với AWS: 5 Bước Tạo Máy Chủ EC2 Đầu Tiên
- Bài 3. Tạo VPC Với Terraform: Xây Dựng Hạ Tầng Mạng Trên AWS
- Bài 4. Quản Lý Tài Nguyên Với Terraform: Sử Dụng Variables Và Outputs
- Bài 5. Tự Động Hóa Triển Khai Với Terraform: Tạo Load Balancer Và Auto Scaling Group
- Bài 6. Sử Dụng Terraform Modules: Tái Sử Dụng Mã Để Quản Lý Hạ Tầng Hiệu Quả
- Bài 7. Terraform Workspaces: Quản Lý Nhiều Môi Trường Hiệu Quả Trên AWS
- Bài 8. Terraform State: Quản Lý Trạng Thái Hạ Tầng Với S3 Và DynamoDB
- Bài 9. Terraform Provisioners: Tự Động Hóa Cấu Hình Web Server Trên EC2
- Bài 10. Terraform CI/CD: Tự Động Triển Khai Hạ Tầng Với GitHub Actions
Bạn Có Đang Tốn Quá Nhiều Thời Gian Để Quản Lý Hạ Tầng?
Học Terraform cơ bản là bước đầu tiên để bạn làm chủ việc quản lý hạ tầng dưới dạng mã (Infrastructure as Code – IaC). Mình từng làm việc trong một team DevOps nhỏ, và mỗi lần cần tạo máy chủ trên AWS, mình phải vào giao diện AWS Console, click qua hàng loạt bước, rồi ghi chú lại cấu hình để đồng bộ với team.
Quá trình này không chỉ tốn thời gian mà còn dễ sai sót. Sau khi tìm hiểu, mình phát hiện Terraform – một công cụ giúp tự động hóa và đồng bộ mọi thứ chỉ với vài dòng code. Trong bài này, mình sẽ hướng dẫn bạn 5 bước cơ bản để làm quen với Terraform: từ cài đặt, viết mã đầu tiên, đến kiểm tra kết quả.
Lưu ý: Hướng dẫn này dùng Terraform phiên bản mới nhất tính đến tháng 3/2025 (Terraform 1.11.2), dựa trên thông tin từ trang chính thức của HashiCorp (https://www.terraform.io/downloads). Mình sẽ tập trung vào việc cài đặt trên macOS, nhưng các bước viết mã và sử dụng Terraform sẽ tương tự trên các hệ điều hành khác.
Học Terraform Cơ Bản: Hướng Dẫn Từng Bước
Bước 1: Cài Đặt Terraform Trên macOS
- Hành động:
- Mở terminal trên macOS.
- Cài đặt Homebrew nếu chưa có (Homebrew là package manager phổ biến trên macOS):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Thêm repository của HashiCorp vào Homebrew:
brew tap hashicorp/tap
- Cài đặt Terraform:
brew install hashicorp/tap/terraform
- Kiểm tra phiên bản Terraform:
terraform --version
- Kết quả thực tế:
- Sau khi chạy lệnh cài đặt Homebrew (bước 2), terminal sẽ hiển thị quá trình cài đặt:
==> Downloading and installing Homebrew... remote: Enumerating objects: 123, done. remote: Counting objects: 100% (123/123), done. remote: Compressing objects: 100% (98/98), done. remote: Total 123 (delta 25), reused 75 (delta 15), pack-reused 0 Receiving objects: 100% (123/123), 45.67 KiB | 1.52 MiB/s, done. Resolving deltas: 100% (25/25), done. ==> Installation successful! ==> Homebrew has enabled anonymous aggregate user behaviour analytics. ==> Next steps: - Run `brew help` to get started - Further documentation: https://docs.brew.sh
(Bạn sẽ thấy thông báo “Installation successful!” và các bước tiếp theo để sử dụng Homebrew).
- Sau khi chạy lệnh
brew tap hashicorp/tap
(bước 3), terminal sẽ hiển thị:==> Tapping hashicorp/tap Cloning into '/opt/homebrew/Library/Taps/hashicorp/homebrew-tap'... remote: Enumerating objects: 1234, done. remote: Counting objects: 100% (1234/1234), done. remote: Compressing objects: 100% (567/567), done. remote: Total 1234 (delta 678), reused 1123 (delta 645), pack-reused 0 Receiving objects: 100% (1234/1234), 234.56 KiB | 2.34 MiB/s, done. Resolving deltas: 100% (678/678), done. Tapped 12 formulae (34 files, 345.6KB).
(Dòng “Tapped 12 formulae” xác nhận repository của HashiCorp đã được thêm thành công).
- Sau khi chạy lệnh
brew install hashicorp/tap/terraform
(bước 4), terminal sẽ hiển thị:==> Installing terraform from hashicorp/tap ==> Downloading https://releases.hashicorp.com/terraform/1.11.2/terraform_1.11.2_darwin_arm64.zip ==> Downloading from https://releases.hashicorp.com/terraform/1.11.2/terraform_1.11.2_darwin_arm64.zip ######################################################################## 100.0% ==> Installing terraform ==> Caveats To activate terraform, add the following to your shell profile (e.g., ~/.zshrc): eval "$(/opt/homebrew/bin/brew shellenv)" ==> Summary 🍺 /opt/homebrew/Cellar/terraform/1.11.2: 3 files, 45.6MB, built in 2 seconds
(Dòng “🍺” và thông tin cài đặt xác nhận Terraform đã được cài đặt thành công).
- Sau khi chạy lệnh
terraform --version
(bước 5), terminal sẽ hiển thị:Terraform v1.11.2 on darwin_arm64
(Dòng đầu tiên cho biết phiên bản Terraform là 1.11.2, và dòng thứ hai xác nhận hệ điều hành là macOS ARM64).
- Sau khi chạy lệnh cài đặt Homebrew (bước 2), terminal sẽ hiển thị quá trình cài đặt:
Bước 2: Tạo Thư Mục Dự Án Và Viết Mã Terraform Đầu Tiên
-
Hành động:
- Tạo một thư mục cho dự án:
mkdir terraform-first-project cd terraform-first-project
- Tạo file
main.tf
:touch main.tf
-
Mở file
main.tf
trong VS Code và dán nội dung sau:terraform { required_providers { local = { source = "hashicorp/local" version = "2.5.1" } } } provider "local" {} resource "local_file" "hello" { filename = "hello.txt" content = "Chào mừng bạn đến với Terraform!" }
Giải thích:
required_providers
: Khai báo providerlocal
(dùng để tạo file trên máy local).provider "local"
: Khởi tạo provider.resource "local_file"
: Tạo một filehello.txt
với nội dung “Chào mừng bạn đến với Terraform!”.
- Tạo một thư mục cho dự án:
-
Kết quả thực tế:
- Sau khi chạy lệnh
mkdir
vàcd
, bạn đã ở trong thư mụcterraform-first-project
. Kiểm tra bằng lệnhpwd
:/Users/user/terraform-first-project
- Sau khi tạo và chỉnh sửa file
main.tf
, thư mục dự án sẽ có cấu trúc:terraform-first-project/ main.tf
(Kiểm tra bằng lệnh
ls
, bạn sẽ thấy chỉ có filemain.tf
trong thư mục). -
Kiểm tra nội dung file
main.tf
bằng lệnh:cat main.tf
Output sẽ là:
terraform { required_providers { local = { source = "hashicorp/local" version = "2.5.1" } } } provider "local" {} resource "local_file" "hello" { filename = "hello.txt" content = "Chào mừng bạn đến với Terraform!" }
(Nội dung file hiển thị đúng như mã đã viết, với các khối
terraform
,provider
, vàresource
được định dạng rõ ràng).
- Sau khi chạy lệnh
Bước 3: Khởi Tạo Dự Án Terraform
- Hành động:
- Trong thư mục
terraform-first-project
, chạy lệnh:terraform init
- Trong thư mục
-
Kết quả thực tế:
-
Terminal sẽ hiển thị quá trình khởi tạo:
Initializing the backend... Initializing provider plugins... - Finding hashicorp/local versions matching "2.5.1"... - Installing hashicorp/local v2.5.1... - Installed hashicorp/local v2.5.1 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure. All Terraform commands should now work. If you ever set or change modules or backend configuration for Terraform, rerun this command to reinitialize your working directory. If you forget, other commands will detect it and remind you to do so if necessary. Your version of Terraform is out of date! The latest version is 1.11.2. You can update by downloading from https://www.terraform.io/downloads.html
(Dòng “Terraform has been successfully initialized!” xác nhận quá trình khởi tạo thành công. Thông báo “Your version of Terraform is out of date!” xuất hiện vì phiên bản Terraform đã cài đặt là 1.11.2, nhưng thông báo này có thể xuất hiện nếu hệ thống phát hiện phiên bản mới hơn trong tương lai).
-
Thư mục dự án sẽ có thêm các file và thư mục mới. Kiểm tra bằng lệnh
ls -R
:terraform-first-project/ .terraform/ .terraform.lock.hcl main.tf terraform-first-project/.terraform: providers/ terraform-first-project/.terraform/providers: registry.terraform.io/ terraform-first-project/.terraform/providers/registry.terraform.io: hashicorp/ terraform-first-project/.terraform/providers/registry.terraform.io/hashicorp: local/ terraform-first-project/.terraform/providers/registry.terraform.io/hashicorp/local: 2.5.1/ terraform-first-project/.terraform/providers/registry.terraform.io/hashicorp/local/2.5.1: darwin_arm64/ terraform-first-project/.terraform/providers/registry.terraform.io/hashicorp/local/2.5.1/darwin_arm64: terraform-provider-local
(Thư mục
.terraform
chứa provider đã tải về, và file.terraform.lock.hcl
lưu thông tin phiên bản provider).
-
Bước 4: Áp Dụng Mã Terraform Để Tạo File
- Hành động:
- Chạy lệnh để xem trước các thay đổi:
terraform plan
- Áp dụng mã để tạo file:
terraform apply
Khi được hỏi “Do you want to perform these actions?”, gõ
yes
và nhấn Enter.
- Chạy lệnh để xem trước các thay đổi:
-
Kết quả thực tế:
-
Sau khi chạy
terraform plan
, terminal sẽ hiển thị kế hoạch thực thi:Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # local_file.hello will be created + resource "local_file" "hello" { + content = "Chào mừng bạn đến với Terraform!" + filename = "hello.txt" + id = (known after apply) } Plan: 1 to add, 0 to change, 0 to destroy.
(Kế hoạch cho thấy Terraform sẽ tạo một file
hello.txt
với nội dung đã định nghĩa). -
Sau khi chạy
terraform apply
và gõyes
, terminal sẽ hiển thị quá trình áp dụng:Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # local_file.hello will be created + resource "local_file" "hello" { + content = "Chào mừng bạn đến với Terraform!" + filename = "hello.txt" + id = (known after apply) } Plan: 1 to add, 0 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes local_file.hello: Creating... local_file.hello: Creation complete after 0s [id=abc123] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
(Dòng “Apply complete! Resources: 1 added, 0 changed, 0 destroyed” xác nhận file đã được tạo).
- Một file
hello.txt
sẽ được tạo trong thư mụcterraform-first-project
. Kiểm tra nội dung file bằng lệnh:cat hello.txt
Output sẽ là:
Chào mừng bạn đến với Terraform!
(Nội dung file hiển thị đúng như đã định nghĩa trong mã Terraform).
-
Bước 5: Xóa Tài Nguyên Để Dọn Dẹp
- Hành động:
- Chạy lệnh để xóa tài nguyên:
terraform destroy
Khi được hỏi “Do you really want to destroy all resources?”, gõ
yes
và nhấn Enter.
- Chạy lệnh để xóa tài nguyên:
-
Kết quả thực tế:
-
Sau khi chạy
terraform destroy
và gõyes
, terminal sẽ hiển thị quá trình xóa:Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: - destroy Terraform will perform the following actions: # local_file.hello will be destroyed - resource "local_file" "hello" { - content = "Chào mừng bạn đến với Terraform!" -> null - filename = "hello.txt" -> null - id = "abc123" -> null } Plan: 0 to add, 0 to change, 1 to destroy. Do you really want to destroy all resources? Terraform will destroy all your managed infrastructure, as shown above. There is no undo. Only 'yes' will be accepted to confirm. Enter a value: yes local_file.hello: Destroying... [id=abc123] local_file.hello: Destruction complete after 0s Destroy complete! Resources: 1 destroyed.
(Dòng “Destroy complete! Resources: 1 destroyed” xác nhận file đã bị xóa).
- File
hello.txt
sẽ bị xóa. Kiểm tra bằng lệnh:ls
Output sẽ là:
.terraform .terraform.lock.hcl main.tf
(Danh sách file không còn
hello.txt
, chỉ còn các file và thư mục liên quan đến Terraform).
-
Kết Quả Đạt Được
- Bạn đã cài đặt thành công Terraform 1.11.2 trên macOS.
- Bạn đã viết và áp dụng mã Terraform đầu tiên, tạo một file
hello.txt
với nội dung “Chào mừng bạn đến với Terraform!”. - Bạn đã xóa tài nguyên để dọn dẹp, đảm bảo không để lại rác trên hệ thống.
- Bạn đã làm quen với các lệnh cơ bản:
terraform init
,plan
,apply
,destroy
.
Lưu Ý Quan Trọng
- Kiểm tra phiên bản Terraform: Nếu lệnh
terraform --version
không hoạt động, kiểm tra lại các bước cài đặt hoặc tải binary trực tiếp từ trang HashiCorp (Terraform Downloads). - Dọn dẹp tài nguyên: Luôn chạy
terraform destroy
sau khi thử nghiệm để tránh để lại tài nguyên không cần thiết. - Phiên bản provider: Hướng dẫn này dùng provider
local
phiên bản 2.5.1. Nếu phiên bản mới hơn được phát hành, bạn có thể cập nhật trong filemain.tf
.