Terraform ทำงานอย่างไร
📖 text • 10 นาทีTerraform ทำงานอย่างไร
Terraform Workflow
การทำงานของ Terraform มี 3 ขั้นตอนหลัก:
Write → Plan → Apply
1. Write — เขียน Configuration
เขียนไฟล์ .tf อธิบาย infrastructure ที่ต้องการ
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-app-data-2024"
}
2. Plan — ตรวจสอบก่อน Apply
Terraform จะเปรียบเทียบ สิ่งที่เขียนไว้ กับ สิ่งที่มีอยู่จริง แล้วบอกว่าจะทำอะไรบ้าง
$ terraform plan
Terraform will perform the following actions:
# aws_s3_bucket.my_bucket will be created
+ resource "aws_s3_bucket" "my_bucket" {
+ bucket = "my-app-data-2024"
+ id = (known after apply)
+ arn = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
เครื่องหมาย + หมายถึง "จะสร้างใหม่" — ดูก่อน ถ้าโอเคค่อย apply
3. Apply — สร้างจริง
$ terraform apply
aws_s3_bucket.my_bucket: Creating...
aws_s3_bucket.my_bucket: Creation complete after 2s [id=my-app-data-2024]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Core Components
Provider
Provider คือ plugin ที่ทำให้ Terraform คุยกับ cloud service ได้
# บอก Terraform ว่าจะใช้ AWS ที่ region ap-southeast-1
provider "aws" {
region = "ap-southeast-1"
}
Provider ยอดนิยม: AWS, Google Cloud, Azure, Cloudflare, GitHub, Kubernetes
Resource
Resource คือสิ่งที่เราต้องการสร้างบน cloud
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
aws_instance= ประเภท resource (EC2)"web"= ชื่อที่เราตั้ง (ใช้อ้างอิงภายใน Terraform)
State
Terraform เก็บ state file (terraform.tfstate) ไว้ track ว่าตอนนี้ infrastructure มีอะไรอยู่บ้าง
Code (desired state) ←→ State File ←→ Real Infrastructure
- เมื่อ
apply→ Terraform เทียบ code กับ state → สร้าง/แก้ไข/ลบ resource - เมื่อ
plan→ Terraform แสดงความแตกต่างระหว่าง code กับ state
Declarative vs Procedural
Terraform ใช้แนวคิด Declarative — เราบอกว่า "ต้องการอะไร" ไม่ได้บอกว่า "ทำยังไง"
# Declarative (Terraform)
# "ฉันต้องการ EC2 3 เครื่อง"
resource "aws_instance" "web" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
ถ้าตอนนี้มี 1 เครื่อง Terraform จะสร้างเพิ่มอีก 2 เครื่อง ถ้าตอนนี้มี 5 เครื่อง Terraform จะลบ 2 เครื่อง
ไม่ต้องเขียน logic เอง — Terraform จัดการให้
ไฟล์สำคัญ
| ไฟล์ | หน้าที่ |
|---|---|
main.tf |
Resource definitions หลัก |
variables.tf |
ประกาศ input variables |
outputs.tf |
ประกาศ output values |
providers.tf |
ตั้งค่า provider |
terraform.tfstate |
State file (ห้ามแก้มือ!) |
.terraform/ |
โฟลเดอร์เก็บ provider plugins |
terraform.tfvars |
ค่า variable (ไม่ควร commit ถ้ามี secret) |
สรุป
- Terraform ทำงาน 3 ขั้น: Write → Plan → Apply
- ใช้ Provider เชื่อมต่อกับ cloud
- ใช้ Resource อธิบายสิ่งที่ต้องการสร้าง
- ใช้ State track infrastructure ปัจจุบัน
- เป็น Declarative — บอกแค่ผลลัพธ์ Terraform จัดการเอง
บทถัดไปเราจะติดตั้ง Terraform แล้วเริ่มใช้งานจริง