Posted on :: 968 Words :: Tags: , , , ,

Testing & Validation

Terraform code của bạn hoạt động hoàn hảo trong dev account. Bạn chạy terraform apply, xem green success messages scroll by, và nghĩ bạn đã xong.

Rồi production xảy ra.

S3 buckets của bạn mở rộng cho internet. EC2 instances chạy sai AMI. Database bạn nghĩ encrypted? Không phải. Và ai đó vừa spin up 47 c5.24xlarge instances ở Tokyo vì không có guardrails.

AWS bill $18,000 đến. Security team của bạn đang có bad day. Và bạn đang học bài học đắt đỏ: testing deployment không giống testing correctness.

Đây là điều không ai nói với bạn: Infrastructure code breaks theo cách application code không. Typo trong Python cho bạn stack trace. Typo trong Terraform cho bạn database exposed publicly passes mọi health check.

Tutorial này chỉ bạn cách catch disasters trước khi chúng cost bạn tiền, compliance violations, hoặc công việc.

📦 Code Examples

Repository: terraform-hcl-tutorial-series This Part: Part 10 - Testing Examples

git clone https://github.com/khuongdo/terraform-hcl-tutorial-series.git
cd terraform-hcl-tutorial-series
git checkout part-10
cd examples/part-10-testing/

# Chạy security scans và tests
tfsec .
terraform init
terraform plan

Tại Sao Testing Infrastructure Thực Sự Quan Trọng

Để tôi đoán: Bạn đang nghĩ "it's just config files, how bad can it be?"

Tôi sẽ nói cho bạn exactly how bad.

Security breach, take one: Developer copies S3 bucket config từ StackOverflow. Quên đổi acl = "public-read". Customer PII leaks. Company lên headlines. GDPR fine: 4% annual revenue.

Cost explosion, take two: Junior engineer sets desired_capacity = 50 thay vì 5 cho autoscaling group. Không ai notice cho đến Monday morning khi AWS đã helpfully bill bạn cho 672 hours compute không cần.

Compliance failure, take three: SOC 2 audit của bạn fails vì 30% RDS instances không encrypted. Bạn thề chúng đã. Hóa ra ai đó copy-paste old Terraform code không enforce encryption.

See the pattern? Đây không phải bugs. Đây là successful deployments của bad decisions.

Bạn cần three layers of defense:

Layer 1: Static Analysis - Scan .tf files mà không deploy gì. Catch obvious mistakes như unencrypted buckets, missing backups, overly permissive security groups. Fast, free, catches 80% problems.

Layer 2: Policy-as-Code - Enforce company rules. "All resources must have CostCenter tag." "RDS instances can't use db.t2.micro in production." Automated compliance checks.

Layer 3: Integration Tests - Actually deploy infrastructure to test account và verify it works. EC2 instance boot? Can reach database? Load balancer health check passing? Expensive nhưng catches what static analysis misses.

Bạn cần cả ba. Đây là cách setup chúng.

Static Analysis: Catch Issues Trước Deployment

Static analysis là first line of defense. Nó scans Terraform files cho known problems mà không deploy gì. No AWS credentials needed. No costs incurred. Just fast feedback về cái gì broken.

tfsec: Your Security Scanner

tfsec biết every common Terraform security mistake. Unencrypted S3 buckets. Security groups open to 0.0.0.0/0. Missing CloudTrail logging. IAM policies với wildcard permissions. It's seen it all.

Install it:

# macOS
brew install tfsec

# Linux
curl -s https://raw.githubusercontent.com/aquasecurity/tfsec/master/scripts/install_linux.sh | bash

# Or use Docker
docker pull aquasec/tfsec

Run it:

tfsec .

Vậy thôi. Nó scans current directory và tells bạn everything sai.

Đây là actual output trông như thế nào:

───────────────────────────────────────────────────────────────
Result #1 HIGH Bucket does not have encryption enabled
───────────────────────────────────────────────────────────────
  main.tf:12-16
───────────────────────────────────────────────────────────────
   12 | resource "aws_s3_bucket" "data_bucket" {
   13 |   bucket = "my-data-bucket"
   14 |   acl    = "private"
   15 | }
───────────────────────────────────────────────────────────────
  Impact:  The bucket objects could be read if compromised
  Resolution: Configure bucket encryption
  More info: https://tfsec.dev/docs/aws/s3/enable-bucket-encryption
───────────────────────────────────────────────────────────────

Fix it:

resource "aws_s3_bucket" "data_bucket" {
  bucket = "my-data-bucket"
}

resource "aws_s3_bucket_server_side_encryption_configuration" "data_bucket" {
  bucket = aws_s3_bucket.data_bucket.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

Chạy tfsec . lần nữa. Green output. Problem solved.

Policy-as-Code: Enforce Your Rules

Static scanners catch known problems. Nhưng chúng không biết company policies của bạn:

  • "All production EC2 instances must have tag CostCenter"
  • "S3 buckets can't be created in ap-southeast-1 (too expensive)"
  • "RDS instances in production can't be smaller than db.t3.medium"

Bạn cần Policy-as-Code. Enter Open Policy Agent.

OPA and Conftest

Open Policy Agent (OPA) là general-purpose policy engine. Bạn viết rules trong Rego language. Conftest applies những rules đó to Terraform plans.

Install Conftest:

# macOS
brew install conftest

# Linux
wget https://github.com/open-policy-agent/conftest/releases/download/v0.46.0/conftest_0.46.0_Linux_x86_64.tar.gz
tar xzf conftest_0.46.0_Linux_x86_64.tar.gz
sudo mv conftest /usr/local/bin/

Create policy: Require CostCenter tags trên everything

Create file policy/tagging.rego:

package main

import future.keywords.contains
import future.keywords.if

# Deny EC2 instances without CostCenter tag
deny[msg] {
  resource := input.resource.aws_instance[name]
  not resource.tags.CostCenter
  msg := sprintf("EC2 instance '%s' missing required tag 'CostCenter'", [name])
}

Integration Testing với Terratest

Static analysis catches configuration mistakes. Nhưng nó can't tell bạn nếu infrastructure actually works.

Questions static analysis can't answer:

  • EC2 instance boot successfully?
  • Application connect được to RDS?
  • Load balancer health check passing?

Bạn cần integration tests. Real deployments to real AWS accounts.

Checkpoint: Did This Stick?

Trước khi move on:

  1. Run tfsec . trên Terraform code. Fix anything marked HIGH hoặc CRITICAL.
  2. Viết one OPA policy enforces company's tagging standards.
  3. Tạo basic Terratest test deploys S3 bucket và validates encryption.
  4. Thêm tfsec to CI/CD pipeline nên nó runs trên every PR.

Tại sao quan trọng: One unencrypted S3 bucket can expose customer data. One missing policy check can cost thousands trong wasted EC2 spend. Testing prevents disasters trước khi reach production.


Series navigation:


Part của "Terraform from Fundamentals to Production" series.