Bài 9: Hiểu Terraform State Quản Lý Trạng Thái Hạ Tầng


Danh sách bài viết trong series Terraform Associate (003)

Terraform State Là Gì?

cd036994-31fe-47e0-bc6c-d8da0c6a1e41

Terraform State là cơ chế mà Terraform sử dụng để lưu trữ trạng thái hiện tại của hạ tầng mà nó quản lý. Trạng thái này được lưu trong file terraform.tfstate, chứa thông tin về các tài nguyên đã triển khai (VD: ID của EC2 instance, tên S3 bucket). Terraform State là cầu nối giữa mã cấu hình (file .tf) và hạ tầng thực tế, giúp Terraform biết được tài nguyên nào đã được tạo, cập nhật, hoặc cần xóa. Hiểu và quản lý state là kỹ năng cốt lõi trong Terraform, được kiểm tra trong kỳ thi Terraform Associate (003), đặc biệt liên quan đến mục tiêu 6 (Implement and Maintain State).

Vai Trò Của Terraform State Trong Quản Lý Hạ Tầng

Terraform State đóng vai trò quan trọng trong quản lý hạ tầng:

  • Đồng bộ hóa hạ tầng: So sánh cấu hình mong muốn (file .tf) với trạng thái thực tế để xác định thay đổi cần áp dụng.
  • Quản lý tài nguyên: Lưu trữ thông tin chi tiết về tài nguyên (VD: ID, thuộc tính), giúp Terraform cập nhật hoặc xóa chính xác.
  • Hỗ trợ phụ thuộc: Đảm bảo thứ tự triển khai tài nguyên dựa trên mối quan hệ phụ thuộc (VD: tạo S3 bucket trước EC2).
  • Tích hợp nhóm làm việc: State cho phép nhiều người cùng làm việc trên cùng hạ tầng khi được lưu trữ từ xa (remote state).

Cấu Trúc Và Nội Dung Của File Terraform State

File Terraform.tfstate

  • Mô tả: File terraform.tfstate là file JSON chứa trạng thái của hạ tầng.
  • Ví dụ nội dung (sau khi triển khai 1 EC2 instance):
    {
    "version": 4,
    "terraform_version": "1.8.4",
    "serial": 1,
    "lineage": "abcd1234-5678-9012-efgh-3456ijklmnop",
    "outputs": {
      "instance_id": {
        "value": "i-1234567890abcdef0",
        "type": "string"
      }
    },
    "resources": [
      {
        "mode": "managed",
        "type": "aws_instance",
        "name": "web_server",
        "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
        "instances": [
          {
            "schema_version": 0,
            "attributes": {
              "id": "i-1234567890abcdef0",
              "ami": "ami-0c55b159cbfafe1f0",
              "instance_type": "t2.micro",
              "public_ip": "54.123.45.67"
            }
          }
        ]
      }
    ]
    }
  • Ý nghĩa:
    • version: Phiên bản định dạng state file.
    • terraform_version: Phiên bản Terraform đã tạo state.
    • resources: Danh sách tài nguyên được quản lý.
    • outputs: Giá trị output được định nghĩa.

File Terraform.tfstate.backup

  • Mô tả: File terraform.tfstate.backup là bản sao lưu tự động của terraform.tfstate trước mỗi lần chạy terraform apply.
  • Ý nghĩa: Giúp khôi phục state nếu có lỗi xảy ra trong quá trình áp dụng thay đổi.

Quản Lý Terraform State

Xem Nội Dung Terraform State

  • Input: Sử dụng lệnh terraform state list để liệt kê tài nguyên trong state.
    terraform state list
  • Output:
    aws_instance.web_server
    aws_s3_bucket.data_bucket
  • Input: Xem chi tiết một tài nguyên trong state.
    terraform state show aws_instance.web_server
  • Output:
    # aws_instance.web_server:
    resource "aws_instance" "web_server" {
      ami           = "ami-0c55b159cbfafe1f0"
      id            = "i-1234567890abcdef0"
      instance_type = "t2.micro"
      public_ip     = "54.123.45.67"
      tags          = {
          "Name" = "WebServer"
      }
    }

Cập Nhật State Với Lệnh Terraform Refresh

  • Mô tả: Lệnh terraform refresh đồng bộ hóa trạng thái trong terraform.tfstate với thực tế, không thay đổi hạ tầng.
  • Input:
    terraform refresh
  • Output (giả sử IP công cộng của EC2 đã thay đổi):

    aws_instance.web_server: Refreshing state... [id=i-1234567890abcdef0]
    [Updated public_ip from "54.123.45.67" to "54.123.45.68"]
    
    No changes. Your infrastructure matches the configuration.
  • Ý nghĩa: State được cập nhật với IP mới.

Xử Lý State Với Lệnh Terraform State

  • Xóa tài nguyên khỏi state:
    • Input:
      terraform state rm aws_instance.web_server
    • Output:
      Removed aws_instance.web_server
      Successfully removed 1 resource instance(s).
    • Ý nghĩa: Xóa tài nguyên khỏi state mà không xóa thực tế.
  • Di chuyển tài nguyên trong state:
    • Input (di chuyển aws_instance.web_server thành aws_instance.new_server):
      terraform state mv aws_instance.web_server aws_instance.new_server
    • Output:
      Move "aws_instance.web_server" to "aws_instance.new_server"
      Successfully moved 1 object(s).
    • Ý nghĩa: Đổi tên tài nguyên trong state.

Ví Dụ Thực Tế: Quản Lý Terraform State

  • File main.tf:

    provider "aws" {
    region     = "us-east-1"
    access_key = "YOUR_ACCESS_KEY"
    secret_key = "YOUR_SECRET_KEY"
    }
    
    resource "aws_s3_bucket" "data_bucket" {
    bucket = "my-unique-bucket-20230518"
    tags = {
      Name = "DataBucket"
    }
    }
    
    resource "aws_instance" "web_server" {
    ami           = "ami-0c55b159cbfafe1f0"
    instance_type = "t2.micro"
    tags = {
      Name = "WebServer"
    }
    
    depends_on = [aws_s3_bucket.data_bucket]
    }
    
    output "instance_id" {
    value = aws_instance.web_server.id
    }
    
    output "bucket_name" {
    value = aws_s3_bucket.data_bucket.bucket
    }
  • Quy trình:

    1. terraform init: Output:

      Initializing provider plugins...
      - Finding hashicorp/aws versions matching "~> 5.0"...
      - Installing hashicorp/aws v5.17.0...
      - Installed hashicorp/aws v5.17.0 (signed by HashiCorp)
      
      Terraform has been successfully initialized!
    2. terraform apply -auto-approve: Output:

      aws_s3_bucket.data_bucket: Creating...
      aws_s3_bucket.data_bucket: Creation complete after 5s [id=my-unique-bucket-20230518]
      
      aws_instance.web_server: Creating...
      aws_instance.web_server: Creation complete after 45s [id=i-1234567890abcdef0]
      
      Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
      
      Outputs:
      instance_id = "i-1234567890abcdef0"
      bucket_name = "my-unique-bucket-20230518"
    3. Xem state:
      terraform state list

      Output:

      aws_instance.web_server
      aws_s3_bucket.data_bucket
    4. Xóa tài nguyên khỏi state:
      terraform state rm aws_instance.web_server

      Output:

      Removed aws_instance.web_server
      Successfully removed 1 resource instance(s).
    5. Cập nhật state:
      terraform refresh

      Output:

      aws_s3_bucket.data_bucket: Refreshing state... [id=my-unique-bucket-20230518]
      No changes. Your infrastructure matches the configuration.

Lưu Ý Quan Trọng Khi Quản Lý Terraform State

  • Sao lưu state: Luôn sao lưu file terraform.tfstateterraform.tfstate.backup trước khi thực hiện thay đổi lớn (VD: state rm).
  • Không chỉnh sửa thủ công: Tránh chỉnh sửa file terraform.tfstate trực tiếp, dễ gây lỗi không đồng bộ.
  • Sử dụng remote state: Trong nhóm làm việc, lưu state từ xa (VD: S3, Terraform Cloud) để tránh xung đột.
  • Bảo mật state: File state chứa thông tin nhạy cảm (VD: ID tài nguyên), mã hóa khi lưu trữ từ xa.
  • Xử lý lỗi state: Nếu state bị hỏng (VD: “Resource not found”), dùng terraform state rm hoặc terraform import để sửa.

Liên Hệ Với Chứng Chỉ Terraform Associate (003)

Kỳ thi Terraform Associate (003) kiểm tra khả năng quản lý state. Bạn cần nắm:

  • Câu hỏi mẫu:
    • “File nào lưu trạng thái hạ tầng trong Terraform?”
      Đáp án: terraform.tfstate.
    • “Lệnh nào dùng để đồng bộ state với thực tế mà không thay đổi hạ tầng?”
      Đáp án: terraform refresh.
    • “Lệnh nào liệt kê tài nguyên trong state?”
      Đáp án: terraform state list.
  • Thực hành: Kỳ thi có thể yêu cầu nhận diện nội dung state hoặc dự đoán output của lệnh terraform state.

Kết Luận

Terraform State là trung tâm của việc quản lý hạ tầng, giúp đồng bộ mã cấu hình với thực tế. Hiểu cách xem, cập nhật, và xử lý state, cùng với thực hành thực tế, sẽ giúp bạn tự tin thi đỗ Terraform Associate (003). Ở bài tiếp theo, chúng ta sẽ tìm hiểu cách sử dụng remote state với backend như S3.

Điều hướng chuỗi bài viết<< Bài 8: Sử Dụng Output Trong Terraform
>> Bài 10: Sử Dụng Remote State Với Backend Như S3 Trong Terraform
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