Bài 2. Học Terraform Với AWS: 5 Bước Tạo Máy Chủ EC2 Đầu Tiên

Bạn Có Đang Tốn Thời Gian Tạo Tài Nguyên AWS Bằng Tay?

Học Terraform với AWS là bước quan trọng để bạn tự động hóa việc quản lý hạ tầng cloud một cách hiệu quả. Sau khi đã làm quen với Terraform ở bài 1, bạn có thể thấy sức mạnh của việc quản lý hạ tầng dưới dạng mã (Infrastructure as Code).

Tuy nhiên, trong thực tế, chúng ta thường làm việc với các nhà cung cấp cloud như AWS, Azure, hay GCP. Việc tạo tài nguyên bằng tay trên AWS Console thường mất nhiều thời gian và dễ sai sót. Trong bài này, mình sẽ hướng dẫn bạn 5 bước để sử dụng Terraform tạo một máy chủ EC2 trên AWS – một trong những dịch vụ phổ biến nhất của AWS – nhanh chóng và hiệu quả.

Học Terraform Với AWS: Hướng Dẫn Từng Bước

Bước 1: Cấu Hình AWS CLI Để Terraform Kết Nối Với AWS

  • Hành động:
    1. Đảm bảo bạn đã cài đặt AWS CLI. Nếu chưa, cài đặt bằng lệnh:
      brew install awscli
    2. Cấu hình AWS CLI với Access Key và Secret Key:
      aws configure

      Khi được hỏi, nhập các thông tin sau:

      • AWS Access Key ID: [Nhập Access Key của bạn]
      • AWS Secret Access Key: [Nhập Secret Key của bạn]
      • Default region name: us-east-1 (hoặc vùng bạn chọn)
      • Default output format: json (hoặc để trống).
  • Kết quả thực tế:
    • Sau khi chạy lệnh brew install awscli, terminal sẽ hiển thị:
      ==> Downloading https://awscli.amazonaws.com/AWSCLIV2-2.15.30.pkg
      ==> Downloading from https://awscli.amazonaws.com/AWSCLIV2-2.15.30.pkg
      ######################################################################## 100.0%
      ==> Installing awscli
      🍺  /opt/homebrew/Cellar/awscli/2.15.30: 1,234 files, 45.6MB, built in 5 seconds

      (Dòng “🍺” xác nhận AWS CLI đã được cài đặt thành công).

    • Sau khi chạy aws configure, terminal sẽ hiển thị:
      AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
      AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
      Default region name [None]: us-east-1
      Default output format [None]: json

      (Thông tin bạn nhập sẽ được lưu vào file ~/.aws/credentials~/.aws/config).

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

  • Hành động:

    1. Tạo một thư mục mới cho dự án:
      mkdir terraform-aws-ec2
      cd terraform-aws-ec2
    2. Tạo file main.tf:
      touch main.tf
    3. 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 = "us-east-1"
      }
      
      resource "aws_instance" "my_first_ec2" {
      ami           = "ami-0c55b159cbfafe1f0" # AMI cho Amazon Linux 2 ở us-east-1
      instance_type = "t2.micro"
      tags = {
       Name = "MyFirstEC2"
      }
      }

      Giải thích:

      • required_providers: Khai báo AWS provider phiên bản 5.0.0.
      • provider "aws": Cấu hình AWS provider với vùng us-east-1.
      • resource "aws_instance": Tạo một máy chủ EC2 với AMI Amazon Linux 2, loại instance t2.micro, và gắn tag Name = "MyFirstEC2".
  • Kết quả thực tế:

    • Sau khi chạy lệnh mkdircd, bạn đã ở trong thư mục terraform-aws-ec2. Kiểm tra bằng lệnh pwd:
      /Users/user/terraform-aws-ec2
    • Sau khi tạo và chỉnh sửa file main.tf, thư mục dự án sẽ có cấu trúc:
      terraform-aws-ec2/
      main.tf

      (Kiểm tra bằng lệnh ls, bạn sẽ thấy chỉ có file main.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 {
       aws = {
         source = "hashicorp/aws"
         version = "5.0.0"
       }
      }
      }
      
      provider "aws" {
      region = "us-east-1"
      }
      
      resource "aws_instance" "my_first_ec2" {
      ami           = "ami-0c55b159cbfafe1f0"
      instance_type = "t2.micro"
      tags = {
       Name = "MyFirstEC2"
      }
      }

      (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-aws-ec2, 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

      (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.my_first_ec2 will be created
      + resource "aws_instance" "my_first_ec2" {
       + ami                          = "ami-0c55b159cbfafe1f0"
       + instance_type                = "t2.micro"
       + id                           = (known after apply)
       + public_ip                    = (known after apply)
       + tags                         = {
           + "Name" = "MyFirstEC2"
         }
       + tags_all                     = {
           + "Name" = "MyFirstEC2"
         }
      }
      
      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 AMI và instance type đã đị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:
      
      # aws_instance.my_first_ec2 will be created
      + resource "aws_instance" "my_first_ec2" {
       + ami                          = "ami-0c55b159cbfafe1f0"
       + instance_type                = "t2.micro"
       + id                           = (known after apply)
       + public_ip                    = (known after apply)
       + tags                         = {
           + "Name" = "MyFirstEC2"
         }
       + tags_all                     = {
           + "Name" = "MyFirstEC2"
         }
      }
      
      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.my_first_ec2: Creating...
      aws_instance.my_first_ec2: Still creating... [10s elapsed]
      aws_instance.my_first_ec2: Creation complete after 15s [id=i-0123456789abcdef0]
      
      Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

      (Dòng “Apply complete! Resources: 1 added, 0 changed, 0 destroyed” xác nhận EC2 đã được tạo).

    • Kiểm tra trên AWS Console (EC2 Dashboard), bạn sẽ thấy một instance mới với tag Name: MyFirstEC2, 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.my_first_ec2 will be destroyed
      - resource "aws_instance" "my_first_ec2" {
       - ami                          = "ami-0c55b159cbfafe1f0" -> null
       - instance_type                = "t2.micro" -> null
       - id                           = "i-0123456789abcdef0" -> null
       - public_ip                    = "54.123.45.67" -> null
       - tags                         = {
           - "Name" = "MyFirstEC2"
         } -> null
       - tags_all                     = {
           - "Name" = "MyFirstEC2"
         } -> 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.my_first_ec2: Destroying... [id=i-0123456789abcdef0]
      aws_instance.my_first_ec2: Still destroying... [10s elapsed]
      aws_instance.my_first_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 MyFirstEC2 sẽ không còn tồn tại.

Kết Quả Đạt Được

  • Bạn đã cấu hình AWS CLI để Terraform kết nối với AWS.
  • Bạn đã tạo thành công một máy chủ EC2 trên AWS bằng Terraform.
  • 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.
  • Bạn đã làm quen với AWS provider và cách quản lý tài nguyên cloud bằng Terraform.

Lưu Ý Quan Trọng

  • AMI phụ thuộc vào vùng: AMI ami-0c55b159cbfafe1f0 chỉ áp dụng cho us-east-1. Nếu bạn dùng vùng khác, hãy tìm AMI phù hợp trên AWS Console hoặc tham khảo tài liệu chính thức của AWS (AWS Documentation).
  • 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ạy terraform destroy sau khi thử nghiệm.
  • Bảo mật Access Key: Không chia sẻ Access Key và Secret Key công khai. Nếu nghi ngờ bị lộ, hãy tạo lại key trên AWS IAM.
Điều hướng chuỗi bài viết<< Bài 1. Học Terraform Cơ Bản: Terraform Là Gì? Cài Đặt Và Viết Mã Đầu Tiên
>> Bài 3. Tạo VPC Với Terraform: Xây Dựng Hạ Tầng Mạng Trên AWS
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