State file เป็นหัวใจของ Terraform เพราะเป็นที่เดียวที่เก็บข้อมูลเชื่อมโยงระหว่าง configuration ที่คุณเขียนกับ resource จริงในโลก cloud หากไฟล์นี้หายหรือเสียหาย tool จะไม่รู้จัก resource ใด ๆ และอาจพยายาม recreate ทั้งหมด ทำให้ผู้ใช้งานเจอ downtime หรือ data loss
บทความนี้อธิบายว่า state file เก็บอะไร, ทำไม local state ไม่เหมาะกับทีม, พื้นฐานของ remote state backend และคำสั่ง state ที่ใช้บ่อยในงานจริง
State File เก็บอะไร
ไฟล์ terraform.tfstate เป็น JSON ที่เก็บ 3 สิ่งหลัก
- Resource mapping — จับคู่
resource.nameใน config กับ ID จริงบน cloud - Attribute values — ค่าปัจจุบันของทุก attribute ของ resource
- Metadata — version, serial, output values, provider dependency
เมื่อรัน plan หรือ apply tool จะเปรียบเทียบ state กับ config กับสถานะจริงบน cloud (refresh) แล้วสร้าง execution plan ให้
ทำไม Local State ไม่เหมาะกับทีม
Local state คือไฟล์ที่อยู่ในเครื่องของคุณเอง ทำงานได้ทันทีไม่ต้อง setup เพิ่ม แต่มีปัญหาเมื่อทำงานเป็นทีม
- ไม่มีใครอื่นเห็น state ที่คุณสร้าง ต้อง copy-paste ไฟล์ส่งกัน
- ถ้าสอง คน apply พร้อมกันโดยใช้ state คนละ copy จะเกิด drift หรือ duplicate resource
- state file มี secret และ attribute sensitive อื่น ๆ ที่ไม่ควร commit เข้า Git
- เครื่อง dev หายหรือเปลี่ยนเครื่อง = state หายไปด้วย
Remote State Backend
Remote backend เก็บ state ไว้ที่ระบบกลาง เช่น S3, Azure Blob, GCS, Cloud edition หรือ Consul ทำให้ทุกคนในทีมใช้ state เดียวกัน มีความสามารถเพิ่มเช่น state locking, versioning และ encryption ที่ backend รองรับ
# backend.tf — กำหนด S3 backend
terraform {
backend "s3" {
bucket = "mycompany-tfstate"
key = "production/network/terraform.tfstate"
region = "ap-southeast-1"
encrypt = true
dynamodb_table = "tf-state-lock"
}
}
หลังเพิ่ม backend block ต้องรัน terraform init เพื่อ migrate state จาก local ไปยัง remote backend
คำสั่ง State ที่ใช้บ่อย
# ดูรายการ resource ทั้งหมดใน state
terraform state list
# ดูรายละเอียด resource ตัวใดตัวหนึ่ง
terraform state show aws_instance.web
# ย้าย resource ไปใน module หรือเปลี่ยนชื่อใน state
terraform state mv aws_instance.old aws_instance.new
# ลบ resource ออกจาก state โดยไม่ลบ resource จริง
terraform state rm aws_instance.experimental
# import resource ที่มีอยู่แล้วเข้ามาใน state
terraform import aws_instance.legacy i-0123456789abcdef0
ข้อควรระวังเรื่อง State
- อย่าแก้ไข
terraform.tfstateด้วยมือ — ใช้คำสั่ง state เสมอ - อย่า commit state file เข้า Git — มี secret และเปลี่ยนทุกครั้งที่ apply
- Backup state file ก่อนทำ operation ที่มีความเสี่ยง เช่น
state rmหรือ migrate backend - Enable versioning บน S3 bucket ที่เก็บ state เพื่อรองรับ rollback
- ใช้ state locking เสมอใน team setting ป้องกัน concurrent apply
สรุป
State file เป็นหัวใจของ configuration ที่เชื่อม resource กับ cloud จริง Local state เหมาะเฉพาะการทดลองส่วนตัว ส่วน production ควรใช้ remote backend เพื่อรองรับทีม มี encryption, versioning และ locking คำสั่ง terraform state ช่วยจัดการ resource ใน state ได้อย่างยืดหยุ่น แต่ต้องใช้ด้วยความระมัดระวังและ backup ก่อนเสมอ บทความถัดไปจะเจาะลึกเรื่อง remote backend บน S3 และ Cloud edition

