terraform-test

작성자: hashicorp

Terraform 테스트 작성 및 실행을 위한 종합 가이드로, 어설션, 모킹, 모듈 검증을 포함합니다. .tftest.hcl 구문을 사용하여 테스트 파일을 작성하며, plan 또는 apply 모드로 실행되는 run 블록을 지원하고, 선택적 상태 격리와 함께 순차 및 병렬 실행을 지원합니다. 리소스 속성, 출력, 데이터 소스에 대한 조건을 어설션하고, expect_failures를 사용하여 잘못된 입력이 적절히 거부되는지 검증합니다. Mock 제공자(Terraform 1.7.0+)는 인프라 동작을 시뮬레이션합니다...

npx skills add https://github.com/hashicorp/agent-skills --skill terraform-test

Terraform Test

Terraform's built-in testing framework validates that configuration updates don't introduce breaking changes. Tests run against temporary resources, protecting existing infrastructure and state files.

Reference Files

  • references/MOCK_PROVIDERS.md — Mock provider syntax, common defaults, when to use mocks (Terraform 1.7.0+ only — skip if the user's version is below 1.7)
  • references/CI_CD.md — GitHub Actions and GitLab CI pipeline examples
  • references/EXAMPLES.md — Complete example test suite (unit, integration, and mock tests for a VPC module)

Read the relevant reference file when the user asks about mocking, CI/CD integration, or wants a full example.

Core Concepts

  • Test file (.tftest.hcl / .tftest.json): Contains run blocks that validate your configuration
  • Run block: A single test scenario with optional variables, providers, and assertions
  • Assert block: Conditions that must be true for the test to pass
  • Mock provider: Simulates provider behavior without real infrastructure (Terraform 1.7.0+)
  • Test modes: apply (default, creates real resources) or plan (validates logic only)

File Structure

my-module/
├── main.tf
├── variables.tf
├── outputs.tf
└── tests/
    ├── defaults_unit_test.tftest.hcl         # plan mode — fast, no resources
    ├── validation_unit_test.tftest.hcl        # plan mode
    └── full_stack_integration_test.tftest.hcl # apply mode — creates real resources

Use *_unit_test.tftest.hcl for plan-mode tests and *_integration_test.tftest.hcl for apply-mode tests so they can be filtered separately in CI.

Test File Structure

# Optional: test-wide settings
test {
  parallel = true  # Enable parallel execution for all run blocks (default: false)
}

# Optional: file-level variables (highest precedence, override all other sources)
variables {
  aws_region    = "us-west-2"
  instance_type = "t2.micro"
}

# Optional: provider configuration
provider "aws" {
  region = var.aws_region
}

# Required: at least one run block
run "test_default_configuration" {
  command = plan

  assert {
    condition     = aws_instance.example.instance_type == "t2.micro"
    error_message = "Instance type should be t2.micro by default"
  }
}

Run Block

run "test_name" {
  command  = plan  # or apply (default)
  parallel = true  # optional, since v1.9.0

  # Override file-level variables
  variables {
    instance_type = "t3.large"
  }

  # Reference a specific module
  module {
    source  = "./modules/vpc"  # local or registry only (not git/http)
    version = "5.0.0"          # registry modules only
  }

  # Control state isolation
  state_key = "shared_state"  # since v1.9.0

  # Plan behavior
  plan_options {
    mode    = refresh-only  # or normal (default)
    refresh = true
    replace = [aws_instance.example]
    target  = [aws_instance.example]
  }

  # Assertions
  assert {
    condition     = aws_instance.example.id != ""
    error_message = "Instance should have a valid ID"
  }

  # Expected failures (test passes if these fail)
  expect_failures = [
    var.instance_count
  ]
}

Common Test Patterns

Validate outputs

run "test_outputs" {
  command = plan

  assert {
    condition     = output.vpc_id != null
    error_message = "VPC ID output must be defined"
  }

  assert {
    condition     = can(regex("^vpc-", output.vpc_id))
    error_message = "VPC ID should start with 'vpc-'"
  }
}

Conditional resources

run "test_nat_gateway_disabled" {
  command = plan

  variables {
    create_nat_gateway = false
  }

  assert {
    condition     = length(aws_nat_gateway.main) == 0
    error_message = "NAT gateway should not be created when disabled"
  }
}

Resource counts

run "test_resource_count" {
  command = plan

  variables {
    instance_count = 3
  }

  assert {
    condition     = length(aws_instance.workers) == 3
    error_message = "Should create exactly 3 worker instances"
  }
}

Tags

run "test_resource_tags" {
  command = plan

  variables {
    common_tags = {
      Environment = "production"
      ManagedBy   = "Terraform"
    }
  }

  assert {
    condition     = aws_instance.example.tags["Environment"] == "production"
    error_message = "Environment tag should be set correctly"
  }

  assert {
    condition     = aws_instance.example.tags["ManagedBy"] == "Terraform"
    error_message = "ManagedBy tag should be set correctly"
  }
}

Data sources

run "test_data_source_lookup" {
  command = plan

  assert {
    condition     = data.aws_ami.ubuntu.id != ""
    error_message = "Should find a valid Ubuntu AMI"
  }

  assert {
    condition     = can(regex("^ami-", data.aws_ami.ubuntu.id))
    error_message = "AMI ID should be in correct format"
  }
}

Validation rules

run "test_invalid_environment" {
  command = plan

  variables {
    environment = "invalid"
  }

  expect_failures = [
    var.environment
  ]
}

Sequential tests with dependencies

run "setup_vpc" {
  command = apply

  assert {
    condition     = output.vpc_id != ""
    error_message = "VPC should be created"
  }
}

run "test_subnet_in_vpc" {
  command = plan

  variables {
    vpc_id = run.setup_vpc.vpc_id
  }

  assert {
    condition     = aws_subnet.example.vpc_id == run.setup_vpc.vpc_id
    error_message = "Subnet should be in the VPC from setup_vpc"
  }
}

Plan options (refresh-only, targeted)

run "test_refresh_only" {
  command = plan

  plan_options {
    mode = refresh-only
  }

  assert {
    condition     = aws_instance.example.tags["Environment"] == "production"
    error_message = "Tags should be refreshed correctly"
  }
}

run "test_specific_resource" {
  command = plan

  plan_options {
    target = [aws_instance.example]
  }

  assert {
    condition     = aws_instance.example.instance_type == "t2.micro"
    error_message = "Targeted resource should be planned"
  }
}

Parallel modules

run "test_networking_module" {
  command  = plan
  parallel = true

  module {
    source = "./modules/networking"
  }

  assert {
    condition     = output.vpc_id != ""
    error_message = "VPC should be created"
  }
}

run "test_compute_module" {
  command  = plan
  parallel = true

  module {
    source = "./modules/compute"
  }

  assert {
    condition     = output.instance_id != ""
    error_message = "Instance should be created"
  }
}

State key sharing

run "create_foundation" {
  command   = apply
  state_key = "foundation"

  assert {
    condition     = aws_vpc.main.id != ""
    error_message = "Foundation VPC should be created"
  }
}

run "create_application" {
  command   = apply
  state_key = "foundation"

  variables {
    vpc_id = run.create_foundation.vpc_id
  }

  assert {
    condition     = aws_instance.app.vpc_id == run.create_foundation.vpc_id
    error_message = "Application should use foundation VPC"
  }
}

Cleanup ordering (S3 objects before bucket)

run "create_bucket" {
  command = apply

  assert {
    condition     = aws_s3_bucket.example.id != ""
    error_message = "Bucket should be created"
  }
}

run "add_objects" {
  command = apply

  assert {
    condition     = length(aws_s3_object.files) > 0
    error_message = "Objects should be added"
  }
}

# Cleanup destroys in reverse: objects first, then bucket

Multiple aliased providers

provider "aws" {
  alias  = "primary"
  region = "us-west-2"
}

provider "aws" {
  alias  = "secondary"
  region = "us-east-1"
}

run "test_with_specific_provider" {
  command = plan

  providers = {
    aws = provider.aws.secondary
  }

  assert {
    condition     = aws_instance.example.availability_zone == "us-east-1a"
    error_message = "Instance should be in us-east-1 region"
  }
}

Complex conditions

assert {
  condition = alltrue([
    for subnet in aws_subnet.private :
    can(regex("^10\\.0\\.", subnet.cidr_block))
  ])
  error_message = "All private subnets should use 10.0.0.0/8 CIDR range"
}

Cleanup

Resources are destroyed in reverse run block order after test completion. This matters for dependencies (e.g., S3 objects before bucket). Use terraform test -no-cleanup to skip cleanup for debugging.

Running Tests

terraform test                                        # all tests
terraform test tests/defaults.tftest.hcl             # specific file
terraform test -filter=test_vpc_configuration        # by run block name
terraform test -test-directory=integration-tests     # custom directory
terraform test -verbose                              # detailed output
terraform test -no-cleanup                           # skip resource cleanup

Best Practices

  1. Naming: *_unit_test.tftest.hcl for plan mode, *_integration_test.tftest.hcl for apply mode
  2. Test naming: Use descriptive run block names that explain the scenario being tested
  3. Default to plan: Use command = plan unless you need to test real resource behavior
  4. Use mocks for external dependencies — faster and no credentials needed (see references/MOCK_PROVIDERS.md)
  5. Error messages: Make them specific enough to diagnose failures without running the test again
  6. Negative tests: Use expect_failures to verify validation rules reject bad inputs
  7. Variable coverage: Test different variable combinations to validate all code paths — test variables have the highest precedence and override all other sources
  8. Module sources: Test files only support local paths and registry modules — not git or HTTP URLs
  9. Parallel execution: Use parallel = true for independent tests with different state files
  10. Cleanup: Integration tests destroy resources in reverse run block order automatically; use -no-cleanup for debugging
  11. CI/CD: Run unit tests on every PR, integration tests on merge (see references/CI_CD.md)

Troubleshooting

IssueSolution
Assertion failuresUse -verbose to see actual vs expected values
Missing credentialsUse mock providers for unit tests
Unsupported module sourceConvert git/HTTP sources to local modules
Tests interferingUse state_key or separate modules for isolation
Slow testsUse command = plan and mocks; run integration tests separately

References

hashicorp의 다른 스킬

provider-actions
hashicorp
Plugin Framework를 사용하여 Terraform Provider 작업을 구현합니다. 수명 주기 이벤트(전/후…)에서 실행되는 명령형 작업을 개발할 때 사용합니다.
official
new-terraform-provider
hashicorp
Use this when scaffolding a new Terraform provider with the Plugin Framework: workspace layout, go module setup, provider server main.go, and a provider.go…
official
terraform-test
hashicorp
Comprehensive guide for writing and running Terraform tests. Use when creating test files (.tftest.hcl), writing test scenarios with run blocks, validating…
official
provider-actions
hashicorp
Plugin Framework를 사용하여 리소스 수명 주기 이벤트에서 명령형 Terraform Provider 작업을 구현합니다. 생성 전/후 및 업데이트 전/후 수명 주기 트리거를 지원합니다(소멸 이벤트는 Terraform 1.14.0에서 사용 불가). 올바른 프레임워크 유형, 컬렉션용 ElementType, 입력 검증용 유효성 검사기를 포함한 적절한 스키마 정의가 필요합니다. 장기 실행 작업을 위한 진행 보고, 타임아웃 관리, 포괄적인 오류 처리를 포함합니다. 폴링 및...
official
aws-ami-builder
hashicorp
Packer의 amazon-ebs 빌더로 사용자 지정 Amazon 머신 이미지를 구축합니다. HCL 템플릿과 프로비저너(셸 스크립트, 파일 업로드, 구성 관리)를 사용해 소스 AMI에서 AMI 생성을 자동화합니다. ami_regions를 통한 다중 리전 AMI 배포와 이름, 소유자, 가상화 유형별 유연한 소스 AMI 필터링을 지원합니다. 환경 변수, AWS 자격 증명 파일 또는 IAM 인스턴스 프로파일을 통해 인증하며 템플릿 검증 및 빌드 명령을 포함합니다...
official
new-terraform-provider
hashicorp
Plugin Framework를 사용하여 새로운 Terraform Provider를 스캐폴딩합니다. 표준 "terraform-provider-" 명명 규칙을 따르는 새로운 Go 모듈 워크스페이스를 생성하고 필요한 종속성을 초기화합니다. HashiCorp의 Plugin Framework 패턴을 따르는 템플릿 main.go 파일을 제공하며, 사용자 정의를 위한 TODO 마커가 포함되어 있습니다. 빌드 및 테스트 명령을 실행하여 Provider가 컴파일되고 초기 검사를 통과하는지 확인함으로써 설정을 검증합니다. 새 워크스페이스를 생성하기 전에 의도를 확인하여 워크스페이스 관리를 처리합니다.
official
azure-verified-modules
hashicorp
Azure Terraform 모듈이 AVM 규정을 준수하기 위한 인증 요구 사항 및 모범 사례입니다. 공급자 버전 제약 조건(azurerm >= 4.0, < 5.0; azapi >= 2.0, < 3.0)을 적용하고, git 기반 모듈 참조를 금지하며 고정된 Terraform 레지스트리 소스를 사용하도록 합니다. 모든 식별자에 소문자 스네이크 케이스, 정확한 변수 유형, 반부패 계층 패턴을 통한 개별 출력 속성, 알파벳 순서로 정렬된 로컬 변수를 요구합니다. 새 리소스가 추가될 때 기능 토글 변수를 요구합니다...
official
provider-docs
hashicorp
Terraform 레지스트리를 위한 Terraform 공급자 문서를 HashiCorp 권장 패턴, tfplugindocs 템플릿, 스키마를 사용하여 생성, 업데이트 및 검토합니다.
official