Skip to content

Terraform Cheatsheet cho AWS

Terraform là tiêu chuẩn phổ biến cho Infrastructure as Code (IaC). Tài liệu này là cheat sheet nhanh cho command quan trọng, quản lý state và các mẫu resource thường dùng trên AWS.

1. CLI Commands Cơ bản

Workflow

bash
# Khởi tạo project
terraform init

# Format file
terraform fmt -recursive

# Validate syntax
terraform validate

# Plan changes
terraform plan -out=tfplan

# Apply
terraform apply tfplan
# Hoặc auto approve (thận trọng)
terraform apply -auto-approve

# Destroy
terraform destroy

State Management

bash
# Liệt kê resource trong state
terraform state list

# Xem chi tiết 1 resource
terraform state show aws_s3_bucket.my_bucket

# Đổi tên resource trong state
terraform state mv aws_instance.old aws_instance.new

# Bỏ theo dõi resource khỏi state
terraform state rm aws_instance.legacy

# Import resource có sẵn
terraform import aws_s3_bucket.existing_bucket my-bucket-name

Debug

bash
export TF_LOG=DEBUG
export TF_LOG_PATH=./terraform.log

2. Cấu hình AWS Provider

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

provider "aws" {
  region  = "us-east-1"
  profile = "my-profile"

  default_tags {
    tags = {
      Environment = "Production"
      ManagedBy   = "Terraform"
    }
  }
}

provider "aws" {
  alias  = "us-east-1"
  region = "us-east-1"
}

3. Mẫu Resource AWS Cơ bản

VPC và Networking

hcl
resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = "main-vpc"
  }
}

resource "aws_subnet" "public" {
  vpc_id                  = aws_vpc.main.id
  cidr_block              = "10.0.1.0/24"
  map_public_ip_on_launch = true
  availability_zone       = "us-west-2a"
}

resource "aws_internet_gateway" "gw" {
  vpc_id = aws_vpc.main.id
}

Security Group

TIP

Ưu tiên name_prefix thay vì name để Terraform có thể create-before-destroy an toàn hơn.

hcl
resource "aws_security_group" "web" {
  name_prefix = "web-sg-"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port   = 80
    to_port     = 80
    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"]
  }

  lifecycle {
    create_before_destroy = true
  }
}

EC2 Instance

hcl
resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  subnet_id     = aws_subnet.public.id

  vpc_security_group_ids = [aws_security_group.web.id]

  user_data = <<-EOF2
              #!/bin/bash
              echo "Hello, World" > index.html
              python3 -m http.server 80 &
              EOF2

  tags = {
    Name = "web-server"
  }
}

S3 Bucket riêng tư

hcl
resource "aws_s3_bucket" "data" {
  bucket = "my-unique-bucket-name-123"
}

resource "aws_s3_bucket_public_access_block" "data" {
  bucket = aws_s3_bucket.data.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_versioning" "data" {
  bucket = aws_s3_bucket.data.id
  versioning_configuration {
    status = "Enabled"
  }
}

4. Variables và Outputs

variables.tf

hcl
variable "environment" {
  description = "Deployment environment (dev, staging, prod)"
  type        = string
  default     = "dev"

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be dev, staging, or prod."
  }
}

variable "instance_count" {
  type    = number
  default = 1
}

outputs.tf

hcl
output "web_url" {
  description = "Public URL of the web server"
  value       = "http://${aws_instance.web.public_ip}"
}

5. Checklist Best Practices

Production Readiness

Trước khi lên production, nên kiểm tra đầy đủ các mục sau.

  • [ ] Dùng remote state (S3 + DynamoDB lock), không commit terraform.tfstate
  • [ ] Pin version Terraform và provider
  • [ ] Tách file rõ ràng (main.tf, variables.tf, outputs.tf)
  • [ ] Không hardcode secrets (dùng Secrets Manager hoặc TF_VAR_*)
  • [ ] Luôn chạy terraform fmtterraform validate
  • [ ] Dùng module cho thành phần tái sử dụng
  • [ ] Tránh sửa tay resource trên AWS console nếu Terraform đang quản lý

Ví dụ remote backend

hcl
terraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket"
    key            = "prod/app.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Kết luận

Terraform sẽ hiệu quả nhất khi bạn giữ state chuẩn, chuẩn hóa cấu trúc file, và áp dụng kỷ luật versioning + review plan trước mỗi lần apply. Cheatsheet này giúp bạn thao tác nhanh và giảm lỗi vận hành trên AWS.

Được phát hành theo giấy phép MIT.