Giới Thiệu — Tại Sao Cần Tự Động Hóa Hạ Tầng?
Khi tôi bắt đầu hành trình với AI vào năm 2023, việc triển khai một API AI đơn giản từng là cơn ác mộng. Tôi nhớ rõ mình từng mất 3 ngày chỉ để cấu hình server, cài đặt dependencies, và debug các lỗi kết nối. Mỗi lần cần scale lên, tôi lại phải thao tác thủ công từng bước trên console — một quá trình dễ gây ra lỗi và không thể tái lập.
Terraform sinh ra để giải quyết vấn đề đó. Thay vì click chuột trên giao diện cloud provider, bạn viết code — và code đó sẽ tự động tạo ra toàn bộ hạ tầng cho bạn. Trong bài viết này, tôi sẽ hướng dẫn bạn từng bước, từ con số 0, để xây dựng một hệ thống API AI hoàn chỉnh với chi phí tối ưu nhất.
Lưu ý quan trọng: Bài viết này sử dụng HolySheep AI làm ví dụ — nền tảng API AI với chi phí chỉ từ $0.42/1M tokens (DeepSeek V3.2), hỗ trợ thanh toán WeChat/Alipay, và độ trễ dưới 50ms.
Phần 1: Terraform Là Gì? Infrastructure as Code Để Làm Gì?
1.1 Khái niệm đơn giản nhất
Hãy tưởng tượng bạn muốn mở một nhà hàng. Thay vì thuê kiến trúc sư vẽ bản thiết kế, rồi thuê thợ xây, rồi tự đi mua từng viên gạch — bạn chỉ cần có một bản thiết kế chi tiết, và một đội ngũ robot sẽ xây dựng nhà hàng theo đúng bản vẽ đó.
Terraform chính là "đội ngũ robot" đó cho hạ tầng máy chủ. Bạn viết mô tả hạ tầng mong muốn (file .tf), chạy một câu lệnh, và Terraform sẽ tự động tạo ra toàn bộ infrastructure trên cloud.
1.2 Tại sao không làm thủ công?
- Có thể tái lập: Deploy 10 server giống hệt nhau chỉ bằng 1 câu lệnh
- Kiểm soát phiên bản: Lưu code trên Git, xem ai đã thay đổi gì
- Xóa bỏ hoàn toàn: Chạy terraform destroy để xóa sạch hạ tầng
- DRY (Don't Repeat Yourself): Tái sử dụng module cho nhiều dự án
Phần 2: Cài Đặt Môi Trường Từ Con Số 0
2.1 Cài đặt Terraform
Trên macOS:
# Sử dụng Homebrew (nếu chưa có, cài tại https://brew.sh)
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
Xác minh cài đặt thành công
terraform --version
Trên Windows (PowerShell):
# Sử dụng Chocolatey
choco install terraform
Hoặc tải trực tiếp từ https://developer.hashicorp.com/terraform/downloads
Giải nén và thêm vào PATH
Xác minh
terraform --version
Trên Linux (Ubuntu/Debian):
# Thêm HashiCorp GPG key
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
Thêm repository
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
Cài đặt
sudo apt update && sudo apt install terraform
Xác minh
terraform --version
2.2 Cài đặt AWS CLI
Để Terraform có thể tạo tài nguyên trên AWS, bạn cần AWS CLI:
# macOS
brew install awscli
Linux
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
Xác minh
aws --version
2.3 Cấu hình AWS Credentials
# Cấu hình credentials (sẽ được nhắc nhập Access Key, Secret Key)
aws configure
Output mẫu:
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
Phần 3: Cấu Trúc Project Terraform Chuẩn
3.1 Tạo cấu trúc thư mục
ai-api-infra/
├── main.tf # File chính, điểm khởi đầu
├── variables.tf # Khai báo biến
├── outputs.tf # Output sau khi deploy
├── providers.tf # Khai báo providers
├── terraform.tfvars # Giá trị biến cụ thể
├── modules/
│ ├── vpc/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ ├── ec2/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ └── api-server/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
└── scripts/
└── deploy.sh # Script deploy tự động
3.2 File providers.tf — Khai báo nền tảng cloud
# providers.tf
terraform {
required_version = ">= 1.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Project = "ai-api-infra"
Environment = var.environment
ManagedBy = "terraform"
}
}
}
3.3 File variables.tf — Khai báo biến
# variables.tf
variable "aws_region" {
description = "Khu vực AWS để triển khai"
type = string
default = "us-east-1"
}
variable "environment" {
description = "Môi trường triển khai"
type = string
default = "production"
}
variable "instance_type" {
description = "Loại EC2 instance"
type = string
default = "t3.medium"
}
variable "vpc_cidr" {
description = "CIDR block cho VPC"
type = string
default = "10.0.0.0/16"
}
variable "api_port" {
description = "Port chạy API server"
type = number
default = 8000
}
3.4 File terraform.tfvars — Giá trị cụ thể
# terraform.tfvars
aws_region = "us-east-1"
environment = "production"
instance_type = "t3.medium"
vpc_cidr = "10.0.0.0/16"
api_port = 8000
Phần 4: Xây Dựng Hạ Tầng VPC và Network
4.1 Module VPC
# modules/vpc/main.tf
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
enable_dns_support = true
tags = {
Name = "${var.environment}-vpc"
}
}
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = {
Name = "${var.environment}-igw"
}
}
resource "aws_subnet" "public_1" {
vpc = aws_vpc.main.id
cidr_block = var.public_subnet_cidr_1
availability_zone = "${var.aws_region}a"
map_public_ip_on_launch = true
tags = {
Name = "${var.environment}-public-subnet-1"
}
}
resource "aws_subnet" "public_2" {
vpc = aws_vpc.main.id
cidr_block = var.public_subnet_cidr_2
availability_zone = "${var.aws_region}b"
map_public_ip_on_launch = true
tags = {
Name = "${var.environment}-public-subnet-2"
}
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
tags = {
Name = "${var.environment}-public-rt"
}
}
resource "aws_route_table_association" "public_1" {
subnet_id = aws_subnet.public_1.id
route_table_id = aws_route_table.public.id
}
resource "aws_route_table_association" "public_2" {
subnet_id = aws_subnet.public_2.id
route_table_id = aws_route_table.public.id
}
4.2 Variables cho VPC
# modules/vpc/variables.tf
variable "vpc_cidr" {
type = string
}
variable "public_subnet_cidr_1" {
type = string
default = "10.0.1.0/24"
}
variable "public_subnet_cidr_2" {
type = string
default = "10.0.2.0/24"
}
variable "aws_region" {
type = string
}
variable "environment" {
type = string
}
Phần 5: Triển Khai API Server — Kết Nối HolySheep AI
5.1 Tại sao chọn HolyShehe AI?
Trước khi đi vào code, cho phép tôi chia sẻ kinh nghiệm thực tế. Khi tôi tìm kiếm giải pháp API AI, tôi đã thử nghiệm nhiều nền tảng. Kết quả:
- OpenAI GPT-4: $60/1M tokens — quá đắt đỏ cho side projects
- Anthropic Claude: $15/1M tokens — vẫn là gánh nặng
- HolySheep AI: Tỷ giá ¥1 = $1, DeepSeek V3.2 chỉ $0.42/1M tokens — tiết kiệm 85%+
Điểm tôi yêu thích nhất ở HolySheep là độ trễ dưới 50ms — gần như realtime, và hỗ trợ thanh toán WeChat/Alipay rất thuận tiện cho người dùng châu Á.
Đăng ký tại đây để nhận tín dụng miễn phí khi bắt đầu.
5.2 Module API Server
# modules/api-server/main.tf
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
}
resource "aws_security_group" "api" {
name = "${var.environment}-api-sg"
description = "Security group cho API server"
vpc_id = var.vpc_id
ingress {
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "HTTPS"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "API Port"
from_port = var.api_port
to_port = var.api_port
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
description = "Outbound all"
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "${var.environment}-api-sg"
}
}
resource "aws_instance" "api_server" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids = [aws_security_group.api.id]
user_data = templatefile("${path.module}/user_data.sh", {
api_port = var.api_port
holysheep_api_key = var.holysheep_api_key
})
tags = {
Name = "${var.environment}-api-server"
}
}
resource "aws_eip" "api_server" {
instance = aws_instance.api_server.id
domain = "vpc"
}
resource "aws_route53_record" "api" {
zone_id = var.hosted_zone_id
name = "api.${var.domain_name}"
type = "A"
ttl = 300
records = [aws_eip.api_server.public_ip]
}
5.3 User Data Script — Cài đặt tự động khi khởi động
# modules/api-server/user_data.sh
#!/bin/bash
set -e
Cập nhật system
apt-get update -y
apt-get upgrade -y
Cài đặt Python và pip
apt-get install -y python3 python3-pip python3-venv nginx certbot
Tạo user cho ứng dụng
useradd -m -s /bin/bash apiuser
Tạo thư mục ứng dụng
mkdir -p /opt/ai-api
chown apiuser:apiuser /opt/ai-api
Clone hoặc tạo ứng dụng (thay thế bằng repo thực tế của bạn)
cat > /opt/ai-api/app.py << 'APPEOF'
from flask import Flask, request, jsonify
import os
import requests
app = Flask(__name__)
HolySheep AI Configuration
HOLYSHEEP_API_KEY = os.environ.get('HOLYSHEEP_API_KEY')
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
@app.route('/health')
def health():
return jsonify({"status": "healthy", "service": "ai-api"})
@app.route('/v1/chat/completions', methods=['POST'])
def chat_completions():
headers = {
"Authorization": f"Bearer {HOLYSHEEP_API_KEY}",
"Content-Type": "application/json"
}
data = request.get_json()
try:
response = requests.post(
f"{HOLYSHEEP_BASE_URL}/chat/completions",
headers=headers,
json=data,
timeout=30
)
return response.json(), response.status_code
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/v1/models', methods=['GET'])
def list_models():
headers = {
"Authorization": f"Bearer {HOLYSHEEP_API_KEY}"
}
try:
response = requests.get(
f"{HOLYSHEEP_BASE_URL}/models",
headers=headers,
timeout=10
)
return response.json(), response.status_code
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=${api_port})
APPEOF
chown apiuser:apiuser /opt/ai-api/app.py
Cài đặt dependencies
cd /opt/ai-api
sudo -u apiuser python3 -m venv venv
sudo -u apiuser /opt/ai-api/venv/bin/pip install flask requests gunicorn
Tạo systemd service
cat > /etc/systemd/system/ai-api.service << 'SVCEOF'
[Unit]
Description=AI API Service
After=network.target
[Service]
User=apiuser
WorkingDirectory=/opt/ai-api
Environment="HOLYSHEEP_API_KEY=${holysheep_api_key}"
ExecStart=/opt/ai-api/venv/bin/gunicorn -w 4 -b 0.0.0.0:${api_port} app:app
Restart=always
[Install]
WantedBy=multi-user.target
SVCEOF
Enable và start service
systemctl daemon-reload
systemctl enable ai-api
systemctl start ai-api
echo "AI API Server deployed successfully!"
5.4 File main.tf chính — Kết hợp tất cả modules
# main.tf
terraform {
required_version = ">= 1.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
Import VPC module
module "vpc" {
source = "./modules/vpc"
vpc_cidr = var.vpc_cidr
public_subnet_cidr_1 = "10.0.1.0/24"
public_subnet_cidr_2 = "
Tài nguyên liên quan
Bài viết liên quan