Bài 4. Quản Lý Tài Nguyên Với Terraform: Sử Dụng Variables Và Outputs

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 variablesoutputs để 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:
    1. Đả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.
    2. 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).

Bước 2: Tạo Thư Mục Dự Án Và Viết Mã Terraform Với Variables

  • Hành động:

    1. Tạo một thư mục mới cho dự án:
      mkdir terraform-variables-outputs
      cd terraform-variables-outputs
    2. 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"
      }
    3. 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ến region, ami, instance_type, và instance_name với giá trị mặc định.
      • provider "aws": Sử dụng biến var.region để định nghĩa vùng AWS.
      • aws_instance: Sử dụng các biến var.ami, var.instance_type, và var.instance_name để tạo EC2.
      • output: Xuất ra instance_idpublic_ip của EC2 để sử dụng sau này.
  • Kết quả thực tế:

    • Sau khi chạy lệnh mkdircd, bạn đã ở trong thư mục terraform-variables-outputs. Kiểm tra bằng lệnh pwd:
      /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 file main.tfvariables.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).

Bước 3: Khởi Tạo Dự Án Terraform

  • Hành động:
    1. Trong thư mục terraform-variables-outputs, chạy lệnh:
      terraform init
  • 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:
    1. Chạy lệnh để xem trước các thay đổi:
      terraform plan
    2. Á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.

  • 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_idpublic_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ái Running.

Bước 5: Xóa Tài Nguyên Để Dọn Dẹp

  • Hành động:
    1. 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.

  • 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

Điều hướng chuỗi bài viết<< Bài 3. Tạo VPC Với Terraform: Xây Dựng Hạ Tầng Mạng Trên AWS
>> Bài 5. Tự Động Hóa Triển Khai Với Terraform: Tạo Load Balancer Và Auto Scaling Group
Chia sẻ bài viết:
Theo dõi
Thông báo của
0 Góp ý
Được bỏ phiếu nhiều nhất
Mới nhất Cũ nhất
Phản hồi nội tuyến
Xem tất cả bình luận