Chuyển tới nội dung chính

Tổ chức cấu hình cho nhiều môi trường

Khi dự án có cả môi trường staging và production, sao chép cấu hình cho từng môi trường dễ dẫn tới sai khác và khó bảo trì. Module Terraform giúp bạn viết cấu hình một lần, rồi dùng lại cho mọi môi trường với kích thước khác nhau. Mỗi môi trường có thư mục và state riêng, nên thay đổi ở staging không bao giờ ảnh hưởng production.

Điều kiện tiên quyết​

Cấu trúc thư mục​

infra/
├── modules/
│ └── web-stack/ # module dùng chung
│ ├── versions.tf
│ ├── variables.tf
│ ├── main.tf
│ └── outputs.tf
└── environments/
├── staging/ # mỗi môi trường một thư mục, một state
│ └── main.tf
└── production/
└── main.tf
Thư mụcNội dung
modules/web-stackSubnet, Instance và Security Group của một môi trường. Không chứa giá trị riêng của môi trường nào.
environments/<tên>Gọi module với giá trị của môi trường đó. Bạn chạy terraform trong thư mục này.

Viết module​

Provider mà module dùng. Thiếu khối này, Terraform tìm nhầm provider hashicorp/fptcloud và báo lỗi khi terraform init:

# modules/web-stack/versions.tf
terraform {
required_providers {
fptcloud = {
source = "fpt-corp/fptcloud"
}
}
}

Biến đầu vào của module:

# modules/web-stack/variables.tf
variable "vpc_id" { type = string }
variable "name_prefix" { type = string }
variable "cidr" { type = string }
variable "image_name" { type = string }
variable "storage_policy_id" { type = string }
variable "ssh_public_key" { type = string }
variable "office_cidr" { type = string }
# modules/web-stack/variables.tf
variable "instance_count" {
type = number
default = 1
}

variable "cpu" {
type = number
default = 2
}

variable "memory_mb" {
type = number
default = 4096
}

variable "attach_security_groups" {
type = bool
default = true
}

Tài nguyên của module. Flavor được chọn theo cpu và memory_mb, nên mỗi môi trường chỉ cần khai báo kích thước:

# modules/web-stack/main.tf
data "fptcloud_flavor" "this" {
vpc_id = var.vpc_id

filter {
key = "cpu"
values = [tostring(var.cpu)]
}
filter {
key = "memory_mb"
values = [tostring(var.memory_mb)]
}
}
# modules/web-stack/main.tf
resource "fptcloud_subnet" "this" {
vpc_id = var.vpc_id
name = "${var.name_prefix}-subnet"
type = "NAT_ROUTED"
cidr = var.cidr
gateway_ip = cidrhost(var.cidr, 1)
}
# modules/web-stack/main.tf
resource "fptcloud_instance" "this" {
count = var.instance_count

vpc_id = var.vpc_id
name = format("%s-web-%02d", var.name_prefix, count.index + 1)
image_name = var.image_name
flavor_name = data.fptcloud_flavor.this.flavors[0].name
subnet_id = fptcloud_subnet.this.id
storage_size_gb = 40
storage_policy_id = var.storage_policy_id
ssh_key = var.ssh_public_key
status = "POWERED_ON"
}
# modules/web-stack/main.tf
data "fptcloud_instance" "this" {
count = var.instance_count

vpc_id = var.vpc_id
id = fptcloud_instance.this[count.index].id
}
# modules/web-stack/main.tf
resource "fptcloud_security_group" "this" {
vpc_id = var.vpc_id
name = "${var.name_prefix}-web-sg"
subnet_id = fptcloud_subnet.this.id
type = "ACL"
apply_to = var.attach_security_groups ? data.fptcloud_instance.this[*].private_ip : []
}
# modules/web-stack/main.tf
locals {
rules = {
http = { port = "80", source = "ALL" }
https = { port = "443", source = "ALL" }
ssh = { port = "22", source = var.office_cidr }
}
}
# modules/web-stack/main.tf
resource "fptcloud_security_group_rule" "this" {
for_each = local.rules

vpc_id = var.vpc_id
security_group_id = fptcloud_security_group.this.id
direction = "INGRESS"
action = "ALLOW"
protocol = "TCP"
port_range = each.value.port
sources = [each.value.source]
description = "Allow ${each.key}"
}

Đầu ra của module:

# modules/web-stack/outputs.tf
output "subnet_id" {
value = fptcloud_subnet.this.id
}

output "private_ips" {
value = data.fptcloud_instance.this[*].private_ip
}

Gọi module từ từng môi trường​

Môi trường staging dùng một Instance nhỏ:

# environments/staging/main.tf
terraform {
required_providers {
fptcloud = {
source = "fpt-corp/fptcloud"
version = "~> 0.3"
}
}
}

provider "fptcloud" {}

data "fptcloud_vpc" "this" {
name = "example-vpc-staging"
}
# environments/staging/main.tf
data "fptcloud_image" "ubuntu" {
vpc_id = data.fptcloud_vpc.this.id

filter {
key = "name"
values = ["UBUNTU-22.04"]
match_by = "substring"
}
}

data "fptcloud_storage_policy" "ssd" {
vpc_id = data.fptcloud_vpc.this.id

filter {
key = "name"
values = ["Premium-SSD"]
}
}
# environments/staging/main.tf
module "web" {
source = "../../modules/web-stack"

vpc_id = data.fptcloud_vpc.this.id
name_prefix = "shop-staging"
cidr = "10.60.1.0/24"
image_name = data.fptcloud_image.ubuntu.images[0].name
storage_policy_id = data.fptcloud_storage_policy.ssd.storage_policies[0].id
ssh_public_key = file(pathexpand("~/.ssh/id_rsa.pub"))
office_cidr = "203.0.113.0/24"
instance_count = 1
}

output "web_private_ips" {
value = module.web.private_ips
}

Môi trường production dùng cùng module, chỉ khác giá trị. Ví dụ, production có 3 Instance, mỗi Instance 4 vCPU và 8 GB RAM:

module "web" {
source = "../../modules/web-stack"

# ... cùng các tham số như staging, đổi giá trị cho production
name_prefix = "shop-production"
cidr = "10.70.1.0/24"
instance_count = 3
cpu = 4
memory_mb = 8192
}

Phần còn lại của environments/production/main.tf giống staging, với tên VPC của production.

Triển khai từng môi trường​

Chạy Terraform trong thư mục của môi trường cần thay đổi:

cd environments/staging
terraform init
terraform plan
terraform apply

Mỗi thư mục có file state riêng, nên terraform destroy ở staging không chạm tới production.

mẹo

Áp dụng thay đổi cho staging trước, kiểm tra, rồi mới áp dụng cho production. Vì hai môi trường dùng chung module, thay đổi đã chạy tốt ở staging sẽ cho kết quả tương tự ở production.

Lưu state ở nơi dùng chung​

Mặc định, state nằm trong file terraform.tfstate trên máy của bạn. Khi nhiều người cùng quản lý hạ tầng, hãy lưu state ở một backend dùng chung, có khóa (locking) và được mã hóa, để mọi người làm việc trên cùng một state. Xem các loại backend trong tài liệu backend của Terraform.

cảnh báo

Không commit file state lên Git. State có thể chứa thông tin nhạy cảm và việc hai người cùng sửa một file state dễ làm hỏng state.

Xóa một môi trường​

Gỡ Security Group trước rồi mới xóa, như trong Dựng hạ tầng ứng dụng web hoàn chỉnh. Để truyền giá trị cho biến của module, thêm attach_security_groups = var.attach_security_groups vào khối module và khai báo biến attach_security_groups trong thư mục môi trường.

Bước tiếp theo​