LinuxUnity LinuxUnity

Bài viết / Terraform

Terraform: Cài đặt, AWS Provider và Resource Lifecycle

Cài đặt Terraform, cấu hình tài khoản AWS và viết file cấu hình đầu tiên — từ terraform init đến terraform apply, tạo và xóa một EC2 instance hoàn toàn bằng code.

20/08/2026 11 phút đọc 8 lượt xem

PP Peter Parker

Trong bài này

Trong bài này, chúng ta sẽ bắt đầu thực hành Terraform trên AWS:

  • Cài đặt Terraform CLI.
  • Cấu hình AWS Credentials.
  • Hiểu Terraform Provider.
  • Viết Terraform configuration đầu tiên.
  • Tạo một EC2 Instance.
  • Làm quen với init, plan, apply, destroy.
  • Hiểu Terraform State ở mức cơ bản.

Cài đặt Terraform

macOS

text
brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Linux (Ubuntu/Debian)

text
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

Windows

text
winget install Hashicorp.Terraform

Sau khi cài đặt xong trên bất kỳ hệ điều hành nào, hãy tắt và mở lại cửa sổ Terminal/PowerShell mới để hệ thống nhận diện cấu hình.

Gõ lệnh sau để kiểm tra:

text
terraform -version

Terraform kết nối AWS như thế nào?

Một điều cần hiểu trước khi viết Terraform:

  • Terraform không đăng nhập vào AWS Console giống con người.
  • Terraform giao tiếp trực tiếp với AWS API thông qua AWS Provider.

Ở đây có hai khái niệm hoàn toàn khác nhau. Ví dụ Terraform yêu cầu Create EC2 → AWS Provider chuyển yêu cầu đó thành AWS API request → AWS IAM kiểm tra: identity này là ai, có quyền ec2:RunInstances không → nếu được phép, AWS mới tạo EC2.

mermaid
flowchart TD
    A["Terraform Configuration"]
    B["Terraform CLI"]
    C["AWS Provider"]
    D["AWS API"]
    E["AWS IAM"]
    F["AWS Resources"]

    A --> B
    B --> C
    C -->|"API Request"| D
    D --> E
    E -->|"Authorized"| F

Cấu hình tài khoản AWS trước khi chạy Terraform

Đây là bước rất nhiều người mới bỏ qua, rồi gặp lỗi khó hiểu như NoCredentialProviders hoặc UnauthorizedOperation ngay ở bước terraform plan. Terraform tự nó không có credentials — nó chỉ gọi API, còn "ai được phép gọi" thì AWS quyết định.

Có 3 cách phổ biến, xếp theo mức độ khuyến nghị:

Cách 1 — AWS CLI configure + shared credentials file

text
aws configure

Lệnh này sẽ hỏi lần lượt:

text
AWS Access Key ID [None]: AKIAxxxxxxxxxxxx
AWS Secret Access Key [None]: xxxxxxxxxxxxxxxxxxxxxxxx
Default region name [None]: ap-southeast-1
Default output format [None]: json

Thông tin lưu vào ~/.aws/credentials và ~/.aws/config. Provider aws tự đọc 2 file này, chỉ cần để provider "aws" {} trống hoặc khai báo region.

Nếu làm việc với nhiều tài khoản (dev/staging/prod), nên dùng named profile:

text
aws configure --profile my-project-dev

Sau đó trỏ Terraform vào đúng profile:

text
provider "aws" {
  region  = "ap-southeast-1"
  profile = "my-project-dev"
}

Cách 2: biến môi trường (phù hợp CI/CD)

text
export AWS_ACCESS_KEY_ID="AKIAxxxxxxxxxxxx"
export AWS_SECRET_ACCESS_KEY="xxxxxxxxxxxxxxxxxxxxxxxx"
export AWS_DEFAULT_REGION="ap-southeast-1"

Cách 3: hardcode trong provider block (chỉ để hiểu, tránh dùng)

text
provider "aws" {
  region     = "ap-southeast-1"
  access_key = "AKIAxxxxxxxxxxxx"
  secret_key = "xxxxxxxxxxxxxxxxxxxxxxxx"
}

Kiểm tra nhanh credentials đang hoạt động trước khi đụng tới Terraform:

text
aws sts get-caller-identity

Nếu báo lỗi Unable to locate credentials, quay lại Cách 1 hoặc Cách 2 trước khi tiếp tục.

Cấu trúc Dự án (Project Path)

Tạo folder cho bài học đầu tiên:

text
mkdir terraform-first-instance && cd terraform-first-instance
touch main.tf

Dự án thực tế thường được chia thành nhiều file theo chức năng:

text
terraform-aws-lab/
├── main.tf          # Quản lý tài nguyên chính
├── variables.tf     # Khai báo biến đầu vào
├── outputs.tf       # Giá trị đầu ra sau khi apply
├── terraform.tfvars # Giá trị thực tế của biến (không commit nếu chứa thông tin nhạy cảm)
└── providers.tf     # Cấu hình Terraform & Provider

Terraform đọc tất cả file .tf trong cùng working directory như một configuration tổng thể. Tên main.tf, variables.tf, outputs.tf chỉ là convention giúp con người tổ chức project dễ hơn, không phải yêu cầu kỹ thuật của Terraform.

Terraform Configuration cơ bản

Tạo file main.tf :

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

provider "aws" {
  region = "ap-southeast-1"
  # profile = "my-project-dev"  # bỏ comment nếu dùng named profile
}
resource "aws_instance" "first_server" {
  ami           = "ami-0672fd5b9210aa093" # Amazon Linux 2023, ap-southeast-1
  instance_type = "t3.micro"

  tags = {
    Name        = "terraform-101"
    Environment = "learning"
  }
}
Khối Ý nghĩa
terraform {} Khai báo version Terraform và providers cần dùng
required_providers Nói Terraform tải AWS provider từ Terraform Registry
provider "aws" {} Cấu hình kết nối AWS (region, credentials — xem phần cấu hình tài khoản ở trên)
resource "aws_instance" "first_server" {} Khai báo 1 EC2 instance. aws_instance là resource type, first_server là tên local trong code

Hiểu Resource Block

Cấu trúc chung: resource "<RESOURCE_TYPE>" "<LOCAL_NAME>"

  • aws_instance được AWS Provider cung cấp.
  • first_server là tên chúng ta đặt bên trong Terraform configuration.

Terraform có thể tham chiếu resource này bằng địa chỉ (Resource Address):  aws_instance.first_server — ví dụ sau này có thể dùng aws_instance.first_server.id  hoặc aws_instance.first_server.public_ip. Đây là nền tảng quan trọng khi infrastructure bắt đầu có nhiều resource phụ thuộc nhau.

Terraform core workflow

Bây giờ chúng ta đã có file main.tf, nhưng chưa có EC2 nào được tạo. Terraform workflow cơ bản nên được hiểu theo luồng:

mermaid
flowchart TD
    A["Write Configuration<br/>*.tf"] --> B["terraform init"]
    B --> C["terraform fmt"]
    C --> D["terraform validate"]
    D --> E["terraform plan"]
    E --> F["Review"]
    F --> G["terraform apply"]
    G --> H["Infrastructure"]

Trong đó:

  • terraform init: Khởi tạo working directory và tải Provider cần thiết.
  • terraform fmt: Chuẩn hóa format của Terraform configuration.
  • terraform validate: Kiểm tra configuration có hợp lệ về syntax và cấu trúc hay không.
  • terraform plan: Xem trước những thay đổi Terraform dự định thực hiện.
  • terraform apply: Thực thi những thay đổi đã được review.

terraform destroy không nằm trong Core Workflow hằng ngày. Đây là một destructive operation dùng khi cần xóa các resource Terraform đang quản lý, ví dụ cleanup sau khi hoàn thành Lab.

Run:terraform init

Terraform đọc:

text
required_providers {
  aws = {
    source = "hashicorp/aws"
  }
}

Sau đó khởi tạo working directory và cài AWS Provider cần thiết. Có thể hình dung:

tf-init

Sau khi chạy thường xuất hiện:

  • .terraform/: chứa working data như Provider binaries. Không commit thư mục này lên Git.
  • .terraform.lock.hcl: lưu dependency selection và checksum của Provider. File này nên commit lên Git.

Run:terraform fmt

Command này tự động chuẩn hóa format của các file .tf. Ví dụ:

text
resource "aws_instance" "first_server" {
  ami           = "AMI_ID"
  instance_type = "t3.micro"
}

Việc chạy terraform fmt trước khi commit giúp code của cả team có format nhất quán.

Có thể xem đây giống như một formatter dành riêng cho HCL:

text
Terraform Code
      │
      ▼
terraform fmt
      │
      ▼
Consistent Formatting

Run:terraform validate

terraform validate kiểm tra Terraform configuration có hợp lệ về mặt syntax và cấu trúc hay không.

Ví dụ workflow đơn giản:

text
Write Code
    │
    ▼
terraform fmt
    │
    ▼
terraform validate
    │
    ▼
terraform plan

Nếu configuration có lỗi rõ ràng, chúng ta nên phát hiện ở bước này trước khi chạy plan.

validate không thay thế plan. validate chủ yếu kiểm tra configuration, còn plan mới tính toán những thay đổi dự kiến đối với infrastructure.

Run:terraform plan

Trước khi chạy lệnh này, hãy đảm bảo bạn đã hoàn tất checklist cấu hình tài khoản AWS ở phần trên — đây là bước Terraform thật sự gọi API AWS để kiểm tra tài nguyên hiện có, nên nếu credentials sai hoặc thiếu quyền, lỗi sẽ xuất hiện ngay tại đây.

Đây là một trong những command quan trọng nhất của Terraform.

Có thể hiểu đơn giản:

tf-plan

Xem trước hành động: + create, ~ update in-place, - destroy, -/+ replace. Là cơ hội phát hiện thay đổi ngoài dự kiến trước khi thực thi.

Ví dụ:

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

Nghĩa là: Create = 1, Change = 0, Destroy = 0

Trong Production:

mermaid
flowchart TD
    A["Change Code"]
    B["terraform plan"]
    C["Review Plan"]
    D{"Approved?"}
    E["terraform apply"]
    F["Fix Code"]

    A --> B
    B --> C
    C --> D
    D -->|"Yes"| E
    D -->|"No"| F
    F --> A

Plan chính là cơ hội để phát hiện một thay đổi ngoài dự kiến trước khi Terraform thực thi nó.

Run:terraform apply

Terraform hiển thị execution plan và yêu cầu xác nhận. Nếu đồng ý:yes

Luồng xử lý ở mức đơn giản:

mermaid
flowchart TD
    A["Terraform Configuration"]
    B["Terraform CLI"]
    C["AWS Provider"]
    D["AWS API"]
    E["EC2 Instance Created"]
    F["Terraform State Updated"]

    A --> B
    B --> C
    C -->|"Create Request"| D
    D --> E
    E -->|"Resource ID / Attributes"| C
    C --> B
    B --> F

Sau khi hoàn thành, Terraform có thể hiển thị:

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Kiểm tra trên AWS Console sẽ thấy EC2 vừa được Terraform tạo.

⚠️ Production Safety: terraform apply thực sự thay đổi infrastructure. Luôn review plan trước khi apply. Với resource chứa dữ liệu hoặc workload Production, cần backup/snapshot phù hợp và nên kiểm thử thay đổi trên Dev/Staging trước.

Vào AWS Console → EC2 → bạn sẽ thấy instance đang running.

tf_3

Terraform State

Sau lần terraform apply đầu tiên với local backend mặc định, Terraform thường tạo file: terraform.tfstate

State giúp Terraform duy trì mapping giữa resource trong configuration và remote object thực tế.

mermaid
flowchart TD
    A[Terraform Configuration]
    B[aws_instance.first_server]
    C[Terraform State]
    D["AWS EC2 Instance<br/>i-xxxxxxxxxxxxxxxxx"]

    A --> B
    B -->|Mapping| C
    C --> D

Nhờ mapping này, Terraform biếtaws_instance.first_serverchính là EC2 đã được tạo trước đó, thay vì hiểu rằng mỗi lần chạy configuration là phải tạo một EC2 mới.

Giả sử ban đầu:

text
tags = {
  Environment = "lab"
}

Sau đó thay thành:

text
tags = {
  Environment = "development"
}

Chạy:terraform plan

Terraform có thể xác định:~ update in-placethay vì tạo lại resource.

Mental model cần nhớ chỉ cần gói gọn như sau:

text
Configuration
Desired State
      │
      ▼
   Terraform
      │
      ├── State
      │
      └── Remote Infrastructure
      │
      ▼
Determine Changes
      │
      ▼
Infrastructure

Ba thành phần quan trọng:

  • Configuration: Infrastructure mà chúng ta mong muốn.
  • State: Mapping giữa Terraform resource và remote object.
  • Remote Infrastructure: Trạng thái thực tế trên AWS mà Provider đọc được.

Terraform là một công cụ Declarative & Stateful: chúng ta khai báo trạng thái mong muốn, Terraform xác định những thay đổi cần thiết để đưa infrastructure về trạng thái đó.

Run:terraform destroy

Terraform tạo destroy plan và yêu cầu xác nhận.

Luồng cơ bản:

mermaid
flowchart TD
    A["Terraform"]
    B["Read Configuration & State"]
    C["Create Destroy Plan"]
    D["AWS Provider"]
    E["AWS API"]
    F["Delete Managed Resources"]
    G["Update Terraform State"]

    A --> B
    B --> C
    C --> D
    D -->|"Delete Request"| E
    E --> F
    F --> G

Sau khi hoàn thành:

Destroy complete!

Cảnh báo: terraform destroy là destructive operation, có thể xóa toàn bộ resource được configuration hiện tại quản lý. Không chạy trên production chỉ để "thử". Trong lab AWS, hãy destroy resource sau khi học xong để tránh phát sinh chi phí.

Tài liệu Terraform CLI Commands: https://developer.hashicorp.com/terraform/cli/commands

.gitignore cho Terraform

Một project Terraform không nên commit local state và working directory:

Tạo file .gitignore:

Ví dụ cơ bản:

text
# Terraform working directory
.terraform/

# Terraform state
*.tfstate
*.tfstate.*

# Crash logs
crash.log
crash.*.log

# Sensitive variable files
*.tfvars
*.tfvars.json

# Local override files
override.tf
override.tf.json
*_override.tf
*_override.tf.json

Nhưng:.terraform.lock.hclnên được commit.

text
main.tf               GIT ✓
.terraform.lock.hcl   GIT ✓
.gitignore            GIT ✓
terraform.tfstate     GIT ✗
.terraform/           GIT ✗

Một lưu ý quan trọng:

Không nên mặc định rằng mọi.tfvarsđều là secret. .tfvars có thể chứa configuration bình thường. Tuy nhiên nếu project dùng .tfvars để chứa credentials, passwords hoặc dữ liệu nhạy cảm thì tuyệt đối không commit chúng.

Ở các project thực tế, nên phân biệt rõ file configuration có thể commit và secret được cung cấp từ secret manager hoặc CI/CD.

Tổng kết

Trong bài này chúng ta đã đi từ một thư mục rỗng đến EC2 đầu tiên được quản lý bằng Terraform. Các khái niệm quan trọng cần nhớ:

Thành phần Vai trò
Terraform CLI Đọc configuration và điều phối Terraform workflow
Provider Cho phép Terraform tương tác với API của platform
Resource Object infrastructure mà Terraform quản lý
Configuration Mô tả desired infrastructure
Plan Xem trước những action Terraform dự định thực hiện
Apply Thực thi những thay đổi
State Theo dõi mapping giữa Terraform resource và remote object
Lock File Ghi lại Provider dependency selections

Điểm quan trọng nhất của bài: Terraform không chỉ là công cụ chạy một chuỗi command để tạo server. Terraform quản lý lifecycle của infrastructure dựa trên configuration, state và Provider API.