Home > Blog > tech

Terraform คืออะไร? สอน Infrastructure as Code (IaC) จัดการ Cloud อัตโนมัติ 2026

terraform infrastructure as code
Terraform Infrastructure as Code Guide 2026
2026-04-08 | tech | 3500 words

การจัดการ Infrastructure ในยุค Cloud Computing เปลี่ยนไปอย่างสิ้นเชิงจากการ Click สร้าง Server ผ่านหน้า Console มาเป็นการเขียน Code กำหนด Infrastructure ทั้งหมด แนวคิดนี้เรียกว่า Infrastructure as Code (IaC) และเครื่องมือที่เป็นมาตรฐานอุตสาหกรรมสำหรับ IaC คือ Terraform ที่สร้างโดย HashiCorp

บทความนี้จะพาคุณเรียนรู้ Terraform ตั้งแต่แนวคิดพื้นฐานของ IaC ไปจนถึงการจัดการ Cloud Infrastructure ระดับ Production ครอบคลุม HCL Syntax, Providers, Resources, State Management, Modules, Workspaces และ Best Practices สำหรับทีม DevOps ในปี 2026

Infrastructure as Code (IaC) คืออะไร?

Infrastructure as Code คือแนวทางในการจัดการและ Provision Infrastructure ผ่านไฟล์ Code แทนการตั้งค่าด้วยมือ (Manual Configuration) ผ่าน Web Console หรือ CLI ทีละคำสั่ง ทำให้ Infrastructure ทั้งหมดถูกบันทึกเป็น Code ที่สามารถ Version Control, Review, Test และ Automate ได้

ปัญหาของการจัดการ Infrastructure แบบเดิม:

IaC แก้ปัญหาเหล่านี้:

Terraform คืออะไร?

Terraform เป็นเครื่องมือ IaC แบบ Open Source ที่สร้างโดย HashiCorp ใช้ภาษา HCL (HashiCorp Configuration Language) ในการกำหนด Infrastructure โดยรองรับ Cloud Provider หลายรายพร้อมกัน ไม่ว่าจะเป็น AWS, Google Cloud Platform (GCP), Microsoft Azure, DigitalOcean, Cloudflare และอีกมากมาย

จุดเด่นหลักของ Terraform ที่ทำให้เป็นมาตรฐานอุตสาหกรรม ได้แก่:

ติดตั้ง Terraform

# macOS
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

# Windows (Chocolatey)
choco install terraform

# Windows (Scoop)
scoop install terraform

# Linux (Ubuntu/Debian)
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform

# ตรวจสอบ
terraform version
terraform -help
IDE Support: ติดตั้ง HashiCorp Terraform Extension สำหรับ VS Code เพื่อได้ Syntax Highlighting, Auto-complete, Format on Save และ Validation

HCL Syntax — ภาษาของ Terraform

HCL (HashiCorp Configuration Language) เป็นภาษาที่ออกแบบให้อ่านง่ายทั้งสำหรับคนและเครื่อง มีโครงสร้างที่ชัดเจน คล้ายกับ JSON แต่อ่านง่ายกว่ามาก

# โครงสร้างพื้นฐานของ HCL
# block_type "label1" "label2" {
#   argument = value
# }

# ตัวอย่าง: กำหนด Provider
provider "aws" {
  region = "ap-southeast-1"  # Singapore
}

# ตัวอย่าง: สร้าง Resource
resource "aws_instance" "web_server" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t3.micro"

  tags = {
    Name        = "WebServer"
    Environment = "production"
  }
}

ชนิดข้อมูลใน HCL

# String
name = "my-server"

# Number
count = 3
price = 9.99

# Boolean
enabled = true

# List
availability_zones = ["ap-southeast-1a", "ap-southeast-1b", "ap-southeast-1c"]

# Map
tags = {
  Name        = "WebServer"
  Environment = "production"
  Team        = "backend"
}

# Object (ซ้อนกัน)
settings = {
  cpu    = 2
  memory = 4096
  disk   = {
    size = 100
    type = "gp3"
  }
}

Providers — เชื่อมต่อ Cloud

Provider คือ Plugin ที่ Terraform ใช้เชื่อมต่อกับ Cloud Provider หรือ Service ต่างๆ แต่ละ Provider มี Resources และ Data Sources เฉพาะของตัวเอง

# AWS Provider
provider "aws" {
  region  = "ap-southeast-1"
  profile = "default"
}

# Google Cloud Provider
provider "google" {
  project = "my-project-id"
  region  = "asia-southeast1"
  zone    = "asia-southeast1-a"
}

# Azure Provider
provider "azurerm" {
  features {}
  subscription_id = "00000000-0000-0000-0000-000000000000"
}

# Required Providers Block (แนะนำให้ระบุ Version)
terraform {
  required_version = ">= 1.9.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    google = {
      source  = "hashicorp/google"
      version = "~> 5.0"
    }
  }
}

Resources และ Data Sources

Resources — สร้าง Infrastructure

Resources คือหัวใจของ Terraform เป็น Block ที่กำหนดว่าต้องการสร้าง Infrastructure อะไร แต่ละ Resource มี Type และ Name ที่ไม่ซ้ำกัน

# สร้าง VPC
resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = "main-vpc"
  }
}

# สร้าง Subnet
resource "aws_subnet" "public" {
  vpc_id            = aws_vpc.main.id  # อ้างอิง Resource อื่น
  cidr_block        = "10.0.1.0/24"
  availability_zone = "ap-southeast-1a"

  tags = {
    Name = "public-subnet"
  }
}

# สร้าง EC2 Instance
resource "aws_instance" "web" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t3.micro"
  subnet_id     = aws_subnet.public.id

  root_block_device {
    volume_size = 20
    volume_type = "gp3"
  }

  tags = {
    Name = "web-server"
  }
}

# สร้าง S3 Bucket
resource "aws_s3_bucket" "assets" {
  bucket = "my-app-assets-2026"

  tags = {
    Name = "App Assets"
  }
}

# สร้าง Security Group
resource "aws_security_group" "web_sg" {
  name        = "web-sg"
  description = "Allow HTTP and HTTPS"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

Data Sources — อ่านข้อมูลที่มีอยู่แล้ว

# อ่าน AMI ล่าสุด
data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]  # Canonical

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-*-24.04-amd64-server-*"]
  }
}

# ใช้ Data Source ใน Resource
resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id  # อ้างอิง Data Source
  instance_type = "t3.micro"
}

# อ่านข้อมูล Availability Zones
data "aws_availability_zones" "available" {
  state = "available"
}

Variables และ Outputs

Input Variables — รับค่าจากภายนอก

# variables.tf
variable "region" {
  description = "AWS Region"
  type        = string
  default     = "ap-southeast-1"
}

variable "instance_type" {
  description = "EC2 Instance Type"
  type        = string
  default     = "t3.micro"

  validation {
    condition     = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type)
    error_message = "Instance type must be t3.micro, t3.small, or t3.medium."
  }
}

variable "environment" {
  description = "Environment name"
  type        = string
}

variable "allowed_cidrs" {
  description = "List of allowed CIDR blocks"
  type        = list(string)
  default     = ["0.0.0.0/0"]
}

variable "tags" {
  description = "Common tags"
  type        = map(string)
  default     = {
    Project = "MyApp"
    ManagedBy = "Terraform"
  }
}

# ใช้ Variable
provider "aws" {
  region = var.region
}

resource "aws_instance" "web" {
  instance_type = var.instance_type
  tags          = merge(var.tags, { Name = "web-server" })
}
# วิธีส่งค่า Variable

# 1. Command line
terraform apply -var="environment=production"

# 2. Variable file (terraform.tfvars)
# terraform.tfvars
environment   = "production"
instance_type = "t3.small"
allowed_cidrs = ["10.0.0.0/8", "172.16.0.0/12"]

# 3. Environment variable
export TF_VAR_environment="production"

# 4. .auto.tfvars (โหลดอัตโนมัติ)
# production.auto.tfvars

Output Values — แสดงผลลัพธ์

# outputs.tf
output "instance_id" {
  description = "EC2 Instance ID"
  value       = aws_instance.web.id
}

output "instance_public_ip" {
  description = "Public IP of the instance"
  value       = aws_instance.web.public_ip
}

output "vpc_id" {
  description = "VPC ID"
  value       = aws_vpc.main.id
}

output "database_endpoint" {
  description = "Database connection string"
  value       = aws_db_instance.main.endpoint
  sensitive   = true  # ไม่แสดงใน CLI output
}

State Management — หัวใจสำคัญ

Terraform State คือไฟล์ที่เก็บข้อมูลว่า Infrastructure จริงตอนนี้เป็นอย่างไร Terraform ใช้ State เปรียบเทียบกับ Code เพื่อคำนวณว่าต้องสร้าง แก้ไข หรือลบ Resource อะไรบ้าง

# State file เริ่มต้นเก็บใน local (terraform.tfstate)
# สำหรับทีม ต้องใช้ Remote State

# Remote State บน S3
terraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket"
    key            = "production/terraform.tfstate"
    region         = "ap-southeast-1"
    dynamodb_table = "terraform-locks"  # สำหรับ State Locking
    encrypt        = true
  }
}

# Remote State บน Google Cloud Storage
terraform {
  backend "gcs" {
    bucket = "my-terraform-state"
    prefix = "production"
  }
}
State Locking: เมื่อใช้ Remote State ต้องเปิด State Locking ด้วย (เช่น DynamoDB สำหรับ AWS) เพื่อป้องกันไม่ให้หลายคน Apply พร้อมกัน ซึ่งจะทำให้ State เสียหายได้
# คำสั่งจัดการ State
terraform state list                         # ดู Resources ทั้งหมดใน State
terraform state show aws_instance.web        # ดูรายละเอียด Resource
terraform state mv aws_instance.web aws_instance.app  # เปลี่ยนชื่อ
terraform state rm aws_instance.web          # ลบ Resource ออกจาก State (ไม่ลบจริง)
terraform state pull                         # ดึง Remote State มาดู
terraform state push                         # Push State ไป Remote

Terraform Workflow: Plan → Apply → Destroy

# 1. Initialize — ดาวน์โหลด Providers และตั้งค่า Backend
terraform init

# 2. Format — จัด Format Code
terraform fmt -recursive

# 3. Validate — ตรวจสอบ Syntax
terraform validate

# 4. Plan — แสดง Preview ของการเปลี่ยนแปลง
terraform plan
terraform plan -out=plan.tfplan  # บันทึก Plan ไว้ Apply ทีหลัง

# 5. Apply — สร้าง/แก้ไข Infrastructure จริง
terraform apply
terraform apply plan.tfplan      # Apply จาก Plan ที่บันทึกไว้
terraform apply -auto-approve    # ไม่ต้องยืนยัน (ใช้ใน CI/CD)

# 6. Destroy — ลบ Infrastructure ทั้งหมด
terraform destroy
terraform destroy -target=aws_instance.web  # ลบเฉพาะ Resource

ตัวอย่าง Plan Output

# terraform plan
Terraform will perform the following actions:

  # aws_instance.web will be created
  + resource "aws_instance" "web" {
      + ami                    = "ami-0abcdef1234567890"
      + instance_type          = "t3.micro"
      + public_ip              = (known after apply)
      + id                     = (known after apply)
      + tags                   = {
          + "Name" = "web-server"
        }
    }

  # aws_instance.old will be destroyed
  - resource "aws_instance" "old" {
      - ami           = "ami-old123" -> null
      - instance_type = "t2.micro"  -> null
    }

  # aws_instance.app will be updated in-place
  ~ resource "aws_instance" "app" {
      ~ instance_type = "t3.micro" -> "t3.small"
    }

Plan: 1 to add, 1 to change, 1 to destroy.

Modules — Code Reuse

Modules ช่วยจัดกลุ่ม Terraform Code ให้ Reuse ได้ ลดการเขียน Code ซ้ำ และทำให้จัดการ Infrastructure ที่ซับซ้อนได้ง่ายขึ้น Module คือ Directory ที่มีไฟล์ .tf อยู่ข้างใน

# โครงสร้าง Module
# modules/
# └── vpc/
#     ├── main.tf
#     ├── variables.tf
#     └── outputs.tf

# modules/vpc/main.tf
resource "aws_vpc" "this" {
  cidr_block           = var.cidr_block
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = merge(var.tags, {
    Name = var.name
  })
}

resource "aws_subnet" "public" {
  count             = length(var.public_subnets)
  vpc_id            = aws_vpc.this.id
  cidr_block        = var.public_subnets[count.index]
  availability_zone = var.availability_zones[count.index]

  tags = {
    Name = "${var.name}-public-${count.index + 1}"
  }
}

# modules/vpc/variables.tf
variable "name" { type = string }
variable "cidr_block" { type = string }
variable "public_subnets" { type = list(string) }
variable "availability_zones" { type = list(string) }
variable "tags" { type = map(string); default = {} }

# modules/vpc/outputs.tf
output "vpc_id" { value = aws_vpc.this.id }
output "public_subnet_ids" { value = aws_subnet.public[*].id }
# ใช้งาน Module
module "vpc" {
  source = "./modules/vpc"

  name               = "production-vpc"
  cidr_block         = "10.0.0.0/16"
  public_subnets     = ["10.0.1.0/24", "10.0.2.0/24"]
  availability_zones = ["ap-southeast-1a", "ap-southeast-1b"]
  tags               = { Environment = "production" }
}

# ใช้ Output จาก Module
resource "aws_instance" "web" {
  subnet_id = module.vpc.public_subnet_ids[0]
}

# ใช้ Module จาก Terraform Registry
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
  azs  = ["ap-southeast-1a", "ap-southeast-1b"]
}

Workspaces — จัดการหลาย Environment

# สร้าง Workspace
terraform workspace new staging
terraform workspace new production

# ดู Workspace ทั้งหมด
terraform workspace list

# สลับ Workspace
terraform workspace select production

# ใช้ Workspace ใน Code
resource "aws_instance" "web" {
  instance_type = terraform.workspace == "production" ? "t3.medium" : "t3.micro"

  tags = {
    Environment = terraform.workspace
  }
}

Terraform Cloud

Terraform Cloud เป็น SaaS ของ HashiCorp ที่ให้บริการ Remote State, Remote Plan/Apply, Team Collaboration และ Policy as Code (Sentinel) เหมาะสำหรับทีมที่ต้องการ Governance และ Collaboration ในการจัดการ Infrastructure

# เชื่อมต่อ Terraform Cloud
terraform {
  cloud {
    organization = "my-organization"

    workspaces {
      name = "my-workspace"
    }
  }
}

# Login
terraform login

ฟีเจอร์หลักของ Terraform Cloud ประกอบด้วย Remote State Management ที่เก็บ State ให้อัตโนมัติพร้อม State Locking และ Remote Execution ที่รัน Plan/Apply บน Cloud แทนเครื่อง Local นอกจากนี้ยังมี VCS Integration ที่เชื่อมกับ GitHub/GitLab ทำ Auto Plan เมื่อมี PR รวมถึง Policy as Code ด้วย Sentinel สำหรับกำหนดกฎบังคับ Infrastructure เช่น ห้ามสร้าง Instance ขนาดใหญ่เกินไป และ Cost Estimation ที่ประมาณค่าใช้จ่ายก่อน Apply ช่วยให้ทีมควบคุมงบประมาณได้

Best Practices สำหรับ Terraform

.gitignore สำหรับ Terraform

# .gitignore
.terraform/
*.tfstate
*.tfstate.*
*.tfvars
!example.tfvars
.terraform.lock.hcl
crash.log
override.tf
override.tf.json
*_override.tf
*_override.tf.json

Terraform vs Pulumi vs CloudFormation

คุณสมบัติTerraformPulumiCloudFormation
ภาษาHCLPython, TS, Go, C#JSON/YAML
Multi-CloudรองรับรองรับAWS เท่านั้น
StateFile-basedCloud-managedAWS-managed
Learning Curveปานกลางง่าย (ถ้ารู้ภาษา)สูง
Communityใหญ่ที่สุดกำลังโตAWS only
ค่าใช้จ่ายFree + Cloud tierFree + paid tierฟรี (AWS)
Dry Runterraform planpulumi previewChange Sets
Importterraform importpulumi importResource Import
ModularityModulesComponentsNested Stacks
TestingTerratestUnit Tests built-incfn-lint
เลือก Tool ไหนดี? Terraform — เมื่อต้องการ Multi-Cloud, Community ใหญ่, มี Module Registry เยอะ | Pulumi — เมื่อต้องการใช้ภาษาที่คุ้นเคย (Python, TypeScript) และต้องการ Unit Test ได้ง่าย | CloudFormation — เมื่อใช้ AWS เท่านั้น และต้องการ Deep Integration กับ AWS Services

CI/CD Integration กับ Terraform

การรวม Terraform เข้ากับ CI/CD Pipeline ทำให้การจัดการ Infrastructure เป็นอัตโนมัติ ลด Human Error และมีขั้นตอน Review ก่อน Apply

GitHub Actions

# .github/workflows/terraform.yml
name: Terraform
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.9.0

      - name: Terraform Init
        run: terraform init

      - name: Terraform Format Check
        run: terraform fmt -check

      - name: Terraform Validate
        run: terraform validate

      - name: Terraform Plan
        run: terraform plan -no-color
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

      - name: Terraform Apply
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: terraform apply -auto-approve
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

GitLab CI

# .gitlab-ci.yml
stages:
  - validate
  - plan
  - apply

validate:
  stage: validate
  script:
    - terraform init
    - terraform fmt -check
    - terraform validate

plan:
  stage: plan
  script:
    - terraform init
    - terraform plan -out=plan.tfplan
  artifacts:
    paths:
      - plan.tfplan

apply:
  stage: apply
  script:
    - terraform init
    - terraform apply plan.tfplan
  when: manual  # ต้องกดยืนยันก่อน Apply
  only:
    - main

ตัวอย่างโปรเจกต์จริง: สร้าง Web Infrastructure บน AWS

# main.tf — สร้าง VPC + EC2 + RDS + ALB
provider "aws" {
  region = "ap-southeast-1"
}

# VPC
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "production-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["ap-southeast-1a", "ap-southeast-1b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]

  enable_nat_gateway = true
  single_nat_gateway = true
}

# Security Group
resource "aws_security_group" "web" {
  name   = "web-sg"
  vpc_id = module.vpc.vpc_id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# EC2 Instance
resource "aws_instance" "web" {
  count         = 2
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.small"
  subnet_id     = module.vpc.private_subnets[count.index]

  vpc_security_group_ids = [aws_security_group.web.id]

  user_data = <<-EOF
              #!/bin/bash
              apt-get update
              apt-get install -y nginx
              systemctl start nginx
              EOF

  tags = {
    Name = "web-server-${count.index + 1}"
  }
}

# RDS Database
resource "aws_db_instance" "main" {
  identifier        = "production-db"
  engine            = "postgres"
  engine_version    = "16.1"
  instance_class    = "db.t3.micro"
  allocated_storage = 20

  db_name  = "myapp"
  username = var.db_username
  password = var.db_password

  vpc_security_group_ids = [aws_security_group.db.id]
  db_subnet_group_name   = aws_db_subnet_group.main.name

  skip_final_snapshot = true
}

คำสั่ง Terraform ที่ใช้บ่อย (Cheatsheet)

คำสั่งหน้าที่
terraform initInitialize โปรเจกต์
terraform planแสดง Preview การเปลี่ยนแปลง
terraform applyสร้าง/แก้ไข Infrastructure
terraform destroyลบ Infrastructure ทั้งหมด
terraform fmtFormat Code
terraform validateตรวจสอบ Syntax
terraform state listดู Resources ใน State
terraform importImport Resource ที่มีอยู่เข้า State
terraform outputแสดง Output Values
terraform workspaceจัดการ Workspaces
terraform graphสร้าง Dependency Graph
terraform taintMark Resource ให้สร้างใหม่

สรุป

Terraform เป็นเครื่องมือที่ขาดไม่ได้สำหรับ DevOps Engineer และ Cloud Engineer ในปัจจุบัน ด้วยแนวคิด Infrastructure as Code ทำให้การจัดการ Cloud Infrastructure เปลี่ยนจากงาน Manual ที่เสี่ยงต่อ Error มาเป็นกระบวนการที่ Reproducible, Versionable และ Automatable

การเริ่มต้นกับ Terraform ไม่ยาก เริ่มจากการสร้าง Resource ง่ายๆ สัก 1-2 ตัว แล้วค่อยขยายไปสู่ Modules, Remote State และ CI/CD Pipeline เมื่อคุณเข้าใจ Workflow ของ Terraform แล้ว คุณจะสามารถจัดการ Infrastructure ที่ซับซ้อนได้อย่างมั่นใจ ไม่ว่าจะเป็น AWS, GCP หรือ Azure ด้วย Code เพียงไม่กี่บรรทัด

สำหรับนักพัฒนาที่ต้องการก้าวเข้าสู่สาย DevOps หรือ Cloud Engineering ในปี 2026 ทักษะ Terraform ถือเป็นสิ่งจำเป็นที่ตลาดงานต้องการสูง เริ่มเรียนรู้วันนี้แล้วคุณจะพร้อมสำหรับโอกาสที่รออยู่


Back to Blog | iCafe Forex | SiamLanCard | Siam2R