Máy chủ web Cloud
figonkingx  

Terraform cơ bản: Bắt đầu với Infrastructure as Code

Infrastructure as Code (IaC) đã trở thành tiêu chuẩn trong DevOps hiện đại, và Terraform của HashiCorp là công cụ phổ biến nhất trong lĩnh vực này. Bài viết này sẽ giúp bạn bắt đầu với Terraform từ những khái niệm cơ bản nhất.

Nội dung chính

Terraform là gì?

Terraform là công cụ IaC cho phép bạn định nghĩa và quản lý infrastructure bằng code. Thay vì click chuột trên console AWS/GCP/Azure, bạn viết file cấu hình và Terraform sẽ tự động tạo, sửa, xóa resources.

Ưu điểm của Terraform:

  • Multi-cloud – Hỗ trợ AWS, GCP, Azure, và hàng trăm providers khác
  • Declarative – Mô tả trạng thái mong muốn, Terraform tự tìm cách đạt được
  • Version control – Infrastructure được quản lý như code, có thể review, rollback
  • Reusable – Modules cho phép tái sử dụng code

Cài đặt Terraform

macOS

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Ubuntu/Debian

wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
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
sudo apt update && sudo apt install terraform

Kiểm tra cài đặt

terraform version
# Terraform v1.8.x

Cấu trúc project Terraform

Một project Terraform cơ bản gồm các file:

my-infrastructure/
├── main.tf          # Resources chính
├── variables.tf     # Khai báo biến
├── outputs.tf       # Output values
├── terraform.tfvars # Giá trị biến (không commit lên git)
└── providers.tf     # Cấu hình providers

Ví dụ: Tạo EC2 instance trên AWS

1. Cấu hình Provider (providers.tf)

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "ap-northeast-1"  # Tokyo
}

2. Khai báo biến (variables.tf)

variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t3.micro"
}

variable "instance_name" {
  description = "Name tag for the instance"
  type        = string
  default     = "my-terraform-instance"
}

3. Định nghĩa Resource (main.tf)

data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.amazon_linux.id
  instance_type = var.instance_type

  tags = {
    Name = var.instance_name
  }
}

resource "aws_security_group" "web_sg" {
  name        = "web-sg"
  description = "Allow HTTP and SSH"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

4. Output (outputs.tf)

output "instance_public_ip" {
  description = "Public IP of EC2 instance"
  value       = aws_instance.web.public_ip
}

output "instance_id" {
  description = "ID of EC2 instance"
  value       = aws_instance.web.id
}

Các lệnh Terraform cơ bản

# Khởi tạo project, download providers
terraform init

# Xem những thay đổi sẽ được thực hiện
terraform plan

# Áp dụng thay đổi (tạo/sửa/xóa resources)
terraform apply

# Xem state hiện tại
terraform show

# Xóa toàn bộ resources
terraform destroy

# Format code
terraform fmt

# Validate cấu hình
terraform validate

State Management

Terraform lưu trạng thái infrastructure trong file terraform.tfstate. Khi làm việc nhóm, nên dùng remote backend:

terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "prod/terraform.tfstate"
    region = "ap-northeast-1"
    
    # Optional: State locking với DynamoDB
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Best Practices

  • Không commit terraform.tfvars – Chứa secrets, credentials
  • Sử dụng remote backend – Cho team collaboration
  • Tách môi trường – dev/, staging/, prod/ riêng biệt
  • Dùng modules – Tái sử dụng code
  • Pin provider versions – Tránh breaking changes
  • Chạy terraform plan trước apply – Review changes

Fullstack Station Tips

Terraform là kỹ năng quan trọng cho bất kỳ developer nào làm việc với cloud. Mình khuyên bạn:

  • Bắt đầu với AWS Free Tier để thực hành không tốn phí
  • Đọc documentation của provider bạn dùng – rất chi tiết
  • Học Terraform Cloud/Enterprise cho production
  • Kết hợp với CI/CD (GitHub Actions, GitLab CI) để tự động hóa

Trong bài tiếp theo, mình sẽ hướng dẫn chi tiết hơn về Terraform với AWS, bao gồm VPC, RDS, và các services phức tạp hơn.

Tham khảo

Comments

Leave A Comment