Infrastructure as Code (IaC) là practice định nghĩa infrastructure bằng code thay vì click-ops. Tuy nhiên, nhiều teams vẫn manage servers manually. Vì vậy, bài viết này giới thiệu Terraform – IaC tool phổ biến nhất – và cách sử dụng nó effectively.
Tại Sao Cần IaC?
Theo HashiCorp, IaC mang lại nhiều lợi ích:
- Version Control – Infrastructure changes tracked trong Git
- Reproducibility – Same code = same infrastructure, every time
- Collaboration – Teams review changes via pull requests
- Documentation – Code IS the documentation
Terraform Basics
HCL Syntax
Terraform sử dụng HashiCorp Configuration Language (HCL). Đây là declarative language dễ đọc. Ví dụ tạo EC2 instance trên AWS:
# Configure AWS Provider
provider "aws" {
region = "ap-southeast-1"
}
# Create EC2 Instance
resource "aws_instance" "web" {
ami = "ami-0abcdef1234567890"
instance_type = "t3.micro"
tags = {
Name = "WebServer"
Environment = "Production"
}
}
Core Commands
# Initialize providers
terraform init
# Preview changes
terraform plan
# Apply changes
terraform apply
# Destroy infrastructure
terraform destroy
State Management
Terraform State là critical concept. State file tracks actual infrastructure và maps to your configuration. Tuy nhiên, storing state locally is risky. Do đó, sử dụng remote backends như S3 hoặc Terraform Cloud:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "ap-southeast-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
Modules: Reusable Infrastructure
Modules cho phép create reusable infrastructure components. Terraform Registry có thousands of community modules. Hơn nữa, bạn có thể tạo private modules cho organization.
Best Practices
- Remote State – Always use remote backend với locking
- Variables – Externalize configs, never hardcode values
- Workspaces – Separate environments (dev, staging, prod)
- CI/CD Integration – Automate terraform plan/apply trong pipelines
Kết Luận
Tóm lại, Terraform là essential skill cho DevOps engineers. Bằng cách define infrastructure as code, bạn có reproducible, version-controlled và auditable infrastructure. Kết hợp với Docker và Kubernetes để có complete cloud-native stack.
Cần tư vấn Infrastructure as Code? Liên hệ KhongGianAI để được hỗ trợ.