What is Infrastructure as Code?
Infrastructure as Code (IaC) คือการใช้ code อธิบาย infrastructure แทนการคลิกใน console — ทำให้สร้างซ้ำได้, version control ได้, ตรวจสอบได้
ปัญหาในยุค Manual Infrastructure
ก่อนยุค IaC การสร้าง server ต้องทำมือทั้งหมด:
- SSH เข้า server
- ติดตั้ง OS
- ติดตั้ง software (nginx, postgres, ฯลฯ)
- ตั้งค่า config
- เปิด firewall
ปัญหาที่เจอบ่อย:
- 😱 Snowflake servers — server แต่ละตัวต่างกัน ไม่มีใครจำได้ว่าทำอะไรไปบ้าง
- 😱 Configuration drift — ตั้งค่าใน prod ต่างจาก dev → bug ที่หาไม่เจอ
- 😱 No audit trail — ใครเปลี่ยนอะไร เมื่อไหร่ ไม่มีบันทึก
- 😱 Disaster recovery ยาก — server พัง = สร้างใหม่หลายชั่วโมง
Infrastructure as Code คืออะไร?
IaC = เขียน infrastructure เป็น code (text file) → commit เข้า Git → รัน tool ให้สร้างจริง
main.tf
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "web-server"
}
}
แค่ไฟล์นี้ + รัน terraform apply = ได้ EC2 instance เลย
ข้อดีของ IaC
| ข้อดี | คำอธิบาย |
|---|---|
| Reproducibility | สร้างซ้ำได้เหมือนเดิม 100% — dev/staging/prod เหมือนกัน |
| Version Control | เก็บใน Git → diff ได้, rollback ได้, blame ได้ |
| Code Review | PR review infrastructure changes ก่อน merge |
| Documentation | code = documentation (อ่าน code = เข้าใจ infra) |
| Speed | scale 100 servers ใน 5 นาที |
| Cost | tear down dev environment ตอนกลางคืน → ประหยัด |
ประเภทของ IaC Tools
1. Declarative (บอกว่าอยากได้อะไร)
- Terraform ⭐ (multi-cloud)
- AWS CloudFormation (AWS-only)
- Pulumi (ใช้ programming language)
- Azure Bicep (Azure-only)
2. Imperative (บอกว่าทำยังไง)
- Ansible (config management + IaC)
- Chef / Puppet (config management)
Declarative vs Imperative
- Declarative = "ฉันอยากได้ EC2 1 ตัว" → tool คิดว่าจะสร้างยังไง
- Imperative = "เปิด terminal → รัน aws ec2 run-instances" → ต้องเขียนทุก step
Terraform เป็น Declarative — เขียนสั้นกว่า แก้ง่ายกว่า
ตัวอย่าง: Manual vs IaC
❌ Manual (AWS Console):
- เปิด AWS Console
- คลิก EC2 → Launch Instance
- เลือก AMI, instance type, key pair, security group
- รอ ~3 นาที
- ทำซ้ำสำหรับ staging + prod 😴
✅ IaC (Terraform):
terraform apply -var environment=dev
terraform apply -var environment=staging
terraform apply -var environment=prod
3 คำสั่ง = 3 environments เหมือนกันเป๊ะ
สรุป
- IaC ทำให้ infrastructure เป็น code → version control + reproducible + testable
- Tools หลัก: Terraform, CloudFormation, Pulumi, Ansible
- Terraform เป็น declarative + multi-cloud เป็นที่นิยมที่สุด
ต่อไปจะมาดูว่า Terraform คืออะไร → What is Terraform?