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
Tại Sao Cần Quản Lý Tài Nguyên Với Terraform Bằng Variables Và Outputs?
Quản lý tài nguyên với Terraform trở nên hiệu quả hơn khi bạn sử dụng variables và outputs để làm cho mã của mình linh hoạt và dễ tái sử dụng. Trong các bài trước, chúng ta đã làm quen với Terraform cơ bản (bài 1), tạo máy chủ EC2 (bài 2), và xây dựng hạ tầng mạng VPC (bài 3).
Tuy nhiên, nếu bạn cần tạo nhiều EC2 với các thông số khác nhau (VD: AMI, instance type, hoặc tag), việc hard-code giá trị trong mã sẽ rất bất tiện. Variables cho phép bạn truyền tham số động, còn outputs giúp bạn lấy thông tin từ tài nguyên đã tạo (VD: public IP của EC2). Trong bài này, mình sẽ hướng dẫn bạn 5 bước để quản lý tài nguyên với Terraform, sử dụng variables và outputs để tạo một EC2 với thông số tùy chỉnh.
Quản Lý Tài Nguyên Với Terraform: Hướng Dẫn Từng Bước
Bước 1: Chuẩn Bị Môi Trường Và Cấu Hình AWS CLI
- Hành động:
- Đảm bảo bạn đã cài đặt Terraform 1.11.2 và AWS CLI. Nếu chưa, tham khảo bài 1 và bài 2 để cài đặt.
- Kiểm tra cấu hình AWS CLI:
aws configure
Đảm bảo bạn đã nhập đúng Access Key, Secret Key, và vùng (VD:
us-east-1
).
- Kết quả thực tế:
- Nếu AWS CLI đã được cấu hình từ trước, bạn có thể kiểm tra bằng lệnh:
aws sts get-caller-identity
Output sẽ là:
{ "UserId": "AIDAXYZ1234567890", "Account": "123456789012", "Arn": "arn:aws:iam::123456789012:user/your-user-name" }
(Output xác nhận AWS CLI đã được cấu hình đúng và có thể kết nối với tài khoản AWS của bạn).
- Nếu AWS CLI đã được cấu hình từ trước, bạn có thể kiểm tra bằng lệnh:
Bước 2: Tạo Thư Mục Dự Án Và Viết Mã Terraform Với Variables
-
Hành động:
- Tạo một thư mục mới cho dự án:
mkdir terraform-variables-outputs cd terraform-variables-outputs
-
Tạo file
variables.tf
để khai báo variables:touch variables.tf
Mở file
variables.tf
trong VS Code và dán nội dung sau:variable "region" { description = "AWS region to deploy resources" type = string default = "us-east-1" } variable "ami" { description = "AMI ID for the EC2 instance" type = string default = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 in us-east-1 } variable "instance_type" { description = "EC2 instance type" type = string default = "t2.micro" } variable "instance_name" { description = "Name tag for the EC2 instance" type = string default = "MyCustomEC2" }
-
Tạo file
main.tf
để sử dụng variables và khai báo outputs:touch main.tf
Mở file
main.tf
trong VS Code và dán nội dung sau:terraform { required_providers { aws = { source = "hashicorp/aws" version = "5.0.0" } } } provider "aws" { region = var.region } resource "aws_instance" "custom_ec2" { ami = var.ami instance_type = var.instance_type tags = { Name = var.instance_name } } output "instance_id" { description = "ID of the EC2 instance" value = aws_instance.custom_ec2.id } output "public_ip" { description = "Public IP of the EC2 instance" value = aws_instance.custom_ec2.public_ip }
Giải thích:
variables.tf
: Khai báo các biếnregion
,ami
,instance_type
, vàinstance_name
với giá trị mặc định.provider "aws"
: Sử dụng biếnvar.region
để định nghĩa vùng AWS.aws_instance
: Sử dụng các biếnvar.ami
,var.instance_type
, vàvar.instance_name
để tạo EC2.output
: Xuất rainstance_id
vàpublic_ip
của EC2 để sử dụng sau này.
- Tạo một thư mục mới cho dự án:
-
Kết quả thực tế:
- Sau khi chạy lệnh
mkdir
vàcd
, bạn đã ở trong thư mụcterraform-variables-outputs
. Kiểm tra bằng lệnhpwd
:/Users/user/terraform-variables-outputs
- Sau khi tạo và chỉnh sửa các file, thư mục dự án sẽ có cấu trúc:
terraform-variables-outputs/ main.tf variables.tf
(Kiểm tra bằng lệnh
ls
, bạn sẽ thấy hai filemain.tf
vàvariables.tf
). -
Kiểm tra nội dung file
variables.tf
bằng lệnh:cat variables.tf
Output sẽ là:
variable "region" { description = "AWS region to deploy resources" type = string default = "us-east-1" } variable "ami" { description = "AMI ID for the EC2 instance" type = string default = "ami-0c55b159cbfafe1f0" } variable "instance_type" { description = "EC2 instance type" type = string default = "t2.micro" } variable "instance_name" { description = "Name tag for the EC2 instance" type = string default = "MyCustomEC2" }
(Nội dung file hiển thị đúng như mã đã viết).
-
Kiểm tra nội dung file
main.tf
bằng lệnh:cat main.tf
Output sẽ là:
terraform { required_providers { aws = { source = "hashicorp/aws" version = "5.0.0" } } } provider "aws" { region = var.region } resource "aws_instance" "custom_ec2" { ami = var.ami instance_type = var.instance_type tags = { Name = var.instance_name } } output "instance_id" { description = "ID of the EC2 instance" value = aws_instance.custom_ec2.id } output "public_ip" { description = "Public IP of the EC2 instance" value = aws_instance.custom_ec2.public_ip }
(Nội dung file hiển thị đúng như mã đã viết).
- Sau khi chạy lệnh
Bước 3: Khởi Tạo Dự Án Terraform
- Hành động:
- Trong thư mục
terraform-variables-outputs
, 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/aws versions matching "5.0.0"... - Installing hashicorp/aws v5.0.0... - Installed hashicorp/aws v5.0.0 (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.
(Dòng “Terraform has been successfully initialized!” xác nhận quá trình khởi tạo thành công).
- 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
:.terraform .terraform.lock.hcl main.tf variables.tf
(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: Xem Trước Và Áp Dụng Mã Terraform Để Tạo EC2
- Hành động:
- Chạy lệnh để xem trước các thay đổi:
terraform plan
- Áp dụng mã để tạo EC2:
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: # aws_instance.custom_ec2 will be created + resource "aws_instance" "custom_ec2" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t2.micro" + id = (known after apply) + public_ip = (known after apply) + tags = { + "Name" = "MyCustomEC2" } + tags_all = { + "Name" = "MyCustomEC2" } } Plan: 1 to add, 0 to change, 0 to destroy.
(Kế hoạch cho thấy Terraform sẽ tạo một máy chủ EC2 với các thông số từ variables).
-
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: # aws_instance.custom_ec2 will be created + resource "aws_instance" "custom_ec2" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t2.micro" + id = (known after apply) + public_ip = (known after apply) + tags = { + "Name" = "MyCustomEC2" } + tags_all = { + "Name" = "MyCustomEC2" } } 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 aws_instance.custom_ec2: Creating... aws_instance.custom_ec2: Still creating... [10s elapsed] aws_instance.custom_ec2: Creation complete after 15s [id=i-0987654321fedcba0] Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: instance_id = "i-0987654321fedcba0" public_ip = "54.123.45.67"
(Dòng “Apply complete! Resources: 1 added, 0 changed, 0 destroyed” xác nhận EC2 đã được tạo. Outputs hiển thị
instance_id
vàpublic_ip
của EC2). - Kiểm tra trên AWS Console (EC2 Dashboard), bạn sẽ thấy một instance mới với tag
Name: MyCustomEC2
, trạng tháiRunning
.
-
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: # aws_instance.custom_ec2 will be destroyed - resource "aws_instance" "custom_ec2" { - ami = "ami-0c55b159cbfafe1f0" -> null - instance_type = "t2.micro" -> null - id = "i-0987654321fedcba0" -> null - public_ip = "54.123.45.67" -> null - tags = { - "Name" = "MyCustomEC2" } -> null - tags_all = { - "Name" = "MyCustomEC2" } -> 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 aws_instance.custom_ec2: Destroying... [id=i-0987654321fedcba0] aws_instance.custom_ec2: Still destroying... [10s elapsed] aws_instance.custom_ec2: Destruction complete after 15s Destroy complete! Resources: 1 destroyed.
(Dòng “Destroy complete! Resources: 1 destroyed” xác nhận EC2 đã bị xóa).
- Kiểm tra lại trên AWS Console, instance
MyCustomEC2
sẽ không còn tồn tại.
-
Kết Quả Đạt Được
- Bạn đã sử dụng variables để quản lý tài nguyên với Terraform một cách linh hoạt, tạo EC2 với các thông số tùy chỉnh.
- Bạn đã sử dụng outputs để lấy thông tin quan trọng (instance ID và public IP) sau khi tạo EC2.
- Bạn đã kiểm tra và xác nhận EC2 hoạt động đúng trên AWS Console.
- Bạn đã xóa tài nguyên để dọn dẹp, tránh phát sinh chi phí không cần thiết.
Lưu Ý Quan Trọng
- Tùy chỉnh variables: Bạn có thể ghi đè giá trị mặc định của variables bằng cách tạo file
terraform.tfvars
hoặc truyền tham số khi chạy lệnhterraform apply
(VD:terraform apply -var "instance_type=t3.micro"
). - Chi phí AWS: Instance
t2.micro
nằm trong Free Tier, nhưng nếu bạn dùng loại instance khác, có thể phát sinh chi phí. Luôn chạyterraform destroy
sau khi thử nghiệm. - Bảo mật outputs: Không hiển thị outputs chứa thông tin nhạy cảm (VD: private key) trong môi trường công khai.
- Ôn lại kiến thức: Xem lại bài 1 Học Terraform Cơ Bản: 5 Bước 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, và bài 3 Tạo VPC Với Terraform: Xây Dựng Hạ Tầng Mạng Trên AWS để nắm vững các khái niệm cơ bản.
- Tài liệu tham khảo: Xem thêm về variables và outputs trong tài liệu chính thức của Terraform (Terraform Variables) và (Terraform Outputs).