Lab 9: Terraform Infrastructure Baseline
Lab นี้สร้าง infrastructure พื้นฐานด้วย Terraform: VPC/Subnet, EC2, Security Group, IAM Role, ALB, Auto Scaling Group, Module, Remote State และ cleanup ด้วย destroy
Learning objectives
- สร้าง VPC และ Subnet ด้วย Terraform
- สร้าง EC2, Security Group และ IAM Role ด้วย Terraform
- สร้าง ALB และ Auto Scaling Group ด้วย Terraform
- แยก reusable code เป็น Module
- ใช้ Remote State และทำลาย Lab Resource ด้วย
terraform destroy
Prerequisites
- ติดตั้ง Terraform และ AWS CLI แล้ว
- ตั้ง AWS CLI profile/SSO สำหรับ account Lab
- มี Budget และรู้ค่าใช้จ่ายของ ALB, NAT Gateway, EC2 และ EBS
- มี S3 bucket สำหรับ remote state หรือสร้าง bucket เฉพาะ Lab
Step 1: Create project structure
infra/
modules/
network/
web-asg/
envs/
dev/
backend.tf
main.tf
variables.tf
terraform.tfvars
Step 2: Configure backend and provider
terraform {
backend "s3" {
bucket = "YOUR_TF_STATE_BUCKET"
key = "learning/dev/terraform.tfstate"
region = "ap-southeast-1"
encrypt = true
use_lockfile = true
}
}
provider "aws" {
region = var.aws_region
}
Step 3: Build network module
- สร้าง VPC CIDR เช่น
10.30.0.0/16 - สร้าง public subnets อย่างน้อย 2 Availability Zones
- สร้าง Internet Gateway และ Route Table สำหรับ public subnets
- Output
vpc_idและpublic_subnet_ids
Step 4: Build web-asg module
- สร้าง Security Group สำหรับ ALB รับ HTTP จาก Internet เฉพาะ Lab
- สร้าง Security Group สำหรับ EC2 รับ traffic จาก ALB Security Group เท่านั้น
- สร้าง IAM Role/Instance Profile สำหรับ EC2
- สร้าง Launch Template พร้อม User Data ติดตั้ง web server
- สร้าง Target Group, ALB Listener และ Auto Scaling Group
Step 5: Run Terraform workflow
cd infra/envs/dev
terraform fmt -recursive
terraform init
terraform validate
terraform plan -out tfplan
terraform apply tfplan
Expected results
- Terraform state ถูกเก็บใน S3 backend
- มี VPC และ public subnets อย่างน้อย 2 AZs
- ALB มี DNS name และ target healthy
- Auto Scaling Group สร้าง EC2 ตาม desired capacity
- Security Group จำกัด EC2 inbound จาก ALB เท่านั้น
Verification steps
terraform output
aws elbv2 describe-target-health --target-group-arn YOUR_TARGET_GROUP_ARN
curl http://YOUR_ALB_DNS_NAME
Troubleshooting
| อาการ | แนวทางแก้ |
|---|---|
terraform init ใช้ backend ไม่ได้ | ตรวจ S3 bucket, Region, IAM permission และ backend key |
| Target unhealthy | ตรวจ User Data, Security Group, Health Check path และ instance logs |
| ALB เปิดไม่ได้ | ตรวจ public subnet route ไป Internet Gateway และ ALB Security Group |
| Plan จะ replace resource สำคัญ | หยุดและอ่าน diff ก่อน apply อาจต้องปรับ lifecycle หรือ config |
Cleanup procedures
- รัน
terraform plan -destroyเพื่อดู resource ที่จะถูกลบ - รัน
terraform destroyใน env Lab - ตรวจ EC2, ALB, Target Group, EBS, ENI และ Security Group ว่าถูกลบแล้ว
- คง state bucket ไว้ถ้าใช้ต่อ หรือ cleanup เฉพาะ object/version ของ Lab เมื่อมั่นใจ
Mini quiz
- ทำไมต้องใช้ remote state ใน Lab ที่ทำกับทีม?
- Security Group ของ EC2 ควรรับ traffic จากที่ใด?
- ทำไมต้องรัน
plan -destroyก่อนdestroy?