Thông thường Terraform dùng để quản lý hạ tầng (Infrastructure as Code) — ví dụ tạo VM, network, AKS, EKS,... Nhưng đôi khi ta cần chạy thêm các lệnh cục bộ (local), chẳng hạn:
- Tự động chạy Docker Compose khi hạ tầng đã sẵn sàng.
- Dừng các container (docker compose down) khi ta terraform destroy.
- Gọi script PowerShell hay bash sau khi apply xong.
→ Khi đó, ta dùng null_resource + local-exec provisioner của Terraform.
Cấu trúc file ví dụ
project-root/
├── backend/
│ └── program.cs
│ └── *.*
├── frontend/
│ ├── app.js
│ └── *.*
└── main.tf
└── compose.yaml
└── *.*Trong đó:
- main.tf: chứa logic Terraform
- compose.yaml: mô tả Docker services
terraform {
required_version = ">= 1.4.0"
required_providers {
null = {
source = "hashicorp/null"
version = "~> 3.0"
}
}
}
resource "null_resource" "run_compose" {
# triggers: đảm bảo Terraform biết khi nào cần re-run
triggers = {
compose_file = file("${path.module}/compose.yaml")
}
# Khi apply
provisioner "local-exec" {
interpreter = ["PowerShell", "-Command"]
working_dir = "${path.module}" # Trỏ tới thư mục chứa compose.yaml
command = "docker compose up -d"
}
# Khi destroy
provisioner "local-exec" {
when = destroy
interpreter = ["PowerShell", "-Command"]
working_dir = "${path.module}"
command = "docker compose down"
}
}🔁 triggerstriggers giúp Terraform nhận biết khi nào cần chạy lại resource này.
Ở ví dụ trên, ta gắn trigger bằng nội dung file Compose
triggers = {
compose_file = file("${path.module}/compose.yaml")
}→ Mỗi khi bạn chỉnh compose.yaml, Terraform thấy file thay đổi → run_compose sẽ chạy lại.
Nếu không có triggers, Terraform sẽ nghĩ resource này “đã apply rồi” và bỏ qua.
🧭 interpreter
Ở đây mình dùng PowerShell thay vì Command Line như ở Part 1. PowerShell hỗ trợ UTF-8, quote/escape tốt. Mình có thử dùng Command Line và báo lỗi
CreateFile src\"\.env: The filename, directory name, or volume label syntax is incorrect. 🧩 command
Là lệnh bạn muốn chạy.
Kết quả
> terraform apply -auto-approve
null_resource.run_compose: Refreshing state... [id=131565378664318425]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement
Terraform will perform the following actions:
# null_resource.run_compose is tainted, so must be replaced
-/+ resource "null_resource" "run_compose" {
~ id = "131565378664318425" -> (known after apply)
# (1 unchanged attribute hidden)
}
Plan: 1 to add, 0 to change, 1 to destroy.
null_resource.run_compose: Destroying... [id=131565378664318425]
null_resource.run_compose: Destruction complete after 0s
null_resource.run_compose: Creating...
null_resource.run_compose: Provisioning with 'local-exec'...
null_resource.run_compose (local-exec): Executing: ["PowerShell" "-Command" "docker-compose up -d"]
...
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
Nhận xét
Đăng nhận xét