What is HCL?
HCL = HashiCorp Configuration Language — ภาษาที่ใช้เขียน Terraform config (และ Vault, Nomad, Packer, Consul)
HCL คืออะไร?
HCL (HashiCorp Configuration Language) เป็น domain-specific language ที่ออกแบบมาให้:
- 👀 อ่านง่ายเหมือน config file
- ✍️ เขียนสนุกกว่า YAML/JSON
- 🤖 machine-friendly — parse ได้รวดเร็ว
- 🔧 มี expression — รองรับ variable, function, condition
HCL มี 2 เวอร์ชัน:
- HCL1 (legacy)
- HCL2 ⭐ (ใช้ตั้งแต่ Terraform 0.12+ — เกือบทุก project ปัจจุบันใช้ตัวนี้)
ทำไมไม่ใช้ YAML/JSON?
YAML
resource:
aws_instance:
web:
ami: ami-12345
instance_type: t2.micro
# comment YAML ใส่ inline ยาก
ปัญหา:
- ❌ indentation sensitive — เผลอ space เกินก็พัง
- ❌ ไม่มี expression / function
- ❌ ไม่รองรับ comment ใน multi-line
JSON
{
"resource": {
"aws_instance": {
"web": {
"ami": "ami-12345",
"instance_type": "t2.micro"
}
}
}
}
ปัญหา:
- ❌ ไม่มี comment เลย (!)
- ❌ ต้องครอบ string ทุกอันด้วย
"" - ❌ trailing comma ไม่ได้ → typo บ่อย
HCL ✅
resource "aws_instance" "web" {
ami = "ami-12345"
instance_type = "t2.micro"
# comment ก็ใส่ได้สบาย
}
ข้อดี:
- ✅ มี comment 3 แบบ (
#,//,/* */) - ✅ ไม่ indentation sensitive
- ✅ รองรับ expression, function, conditional, loop
- ✅ ใช้
=ตรงไปตรงมา
HCL ใช้ที่ไหนบ้าง?
| HashiCorp Product | ใช้ HCL ทำอะไร |
|---|---|
| Terraform ⭐ | Infrastructure config |
| Packer | Build VM/container images |
| Vault | Policy file |
| Nomad | Job specification |
| Consul | Service config |
| Boundary | Identity-aware proxy config |
| Waypoint | App deployment config |
→ เรียน HCL ครั้งเดียว ใช้ได้กับทั้ง ecosystem ของ HashiCorp
HCL vs JSON เป็นเพื่อนกัน
HCL convert ไปเป็น JSON ได้ตรงๆ เพราะ Terraform ใต้ผิวอ่านเป็น JSON
main.tf (HCL):
resource "aws_s3_bucket" "data" {
bucket = "my-bucket"
}
เทียบเท่า main.tf.json (JSON):
{
"resource": {
"aws_s3_bucket": {
"data": {
"bucket": "my-bucket"
}
}
}
}
เมื่อไหร่ใช้ JSON?
ส่วนใหญ่ใช้ HCL — JSON เหมาะตอน generate config จาก script (เช่น Python script สร้าง Terraform config)
ตัวอย่าง HCL Features
1. Expressions
locals {
total = 5 + 3 # arithmetic
name = "${var.env}-server" # interpolation
upper = upper("hello") # function
}
2. Conditional
instance_type = var.env == "prod" ? "t3.large" : "t3.micro"
3. Loop (for)
azs = [for az in data.aws_availability_zones.available.names : az]
4. Dynamic Block
dynamic "ingress" {
for_each = var.allowed_ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
}
}
อย่าเพิ่งกังวลกับ syntax ตอนนี้ — เราจะลงรายละเอียดในหัวข้อถัดไป
Mental Model
มอง HCL เป็น 3 layer:
- Configuration — declare ว่าอยากได้อะไร
- Expressions — คำนวณค่า, อ้างอิง, condition
- Types — type system ที่ต่างจาก dynamic language ทั่วไป
สรุป
- HCL = ภาษาที่ออกแบบมาสำหรับ infrastructure config โดยเฉพาะ
- เด่นกว่า YAML/JSON เพราะมี comment, expression, function
- ใช้กับทั้ง ecosystem HashiCorp (Terraform, Vault, Packer, Nomad)
- HCL2 = version ที่ใช้กันทุกวันนี้ (ตั้งแต่ Terraform 0.12)
ต่อไป → Basic Syntax เรียน syntax พื้นฐานของ HCL