Skip to main content

What is Infrastructure as Code?

Infrastructure as Code (IaC) คือการใช้ code อธิบาย infrastructure แทนการคลิกใน console — ทำให้สร้างซ้ำได้, version control ได้, ตรวจสอบได้

ปัญหาในยุค Manual Infrastructure

ก่อนยุค IaC การสร้าง server ต้องทำมือทั้งหมด:

  1. SSH เข้า server
  2. ติดตั้ง OS
  3. ติดตั้ง software (nginx, postgres, ฯลฯ)
  4. ตั้งค่า config
  5. เปิด 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 ReviewPR review infrastructure changes ก่อน merge
Documentationcode = documentation (อ่าน code = เข้าใจ infra)
Speedscale 100 servers ใน 5 นาที
Costtear 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):

  1. เปิด AWS Console
  2. คลิก EC2 → Launch Instance
  3. เลือก AMI, instance type, key pair, security group
  4. รอ ~3 นาที
  5. ทำซ้ำสำหรับ 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?