terraform-test은(는) 무엇을 하나요?
Terraform 테스트 작성 및 실행을 위한 종합 가이드입니다. 테스트 파일(.tftest.hcl) 생성, run 블록으로 테스트 시나리오 작성, 어설션(assertion)을 통한 인프라 동작 검증, 프로바이더 및 데이터 소스 모킹(mocking), 모듈 출력 및 리소스 구성 테스트, Terraform 테스트 구문 및 실행 문제 해결 시 사용하세요.
소개
Terraform 테스트는 인프라 구성을 안전하게 검증할 수 있는 프레임워크를 제공합니다. .tftest.hcl 파일을 통해 선언적인 방식으로 테스트를 정의하며, 실제 리소스 생성 전에 동작을 확인할 수 있습니다.
테스트 파일 구조
모든 Terraform 테스트 파일은 확장자가 .tftest.hcl이며, 다음과 같은 기본 구조를 가집니다:
# main.tftest.hcl
run "resource_creation_test" {
# 테스트 실행 블록
}
provider "aws" {
# 프로바이더 모킹
}
run 블록
run 블록은 테스트 시나리오를 정의하는 핵심 구성 요소입니다. 각 run 블록은 Terraform 명령어(apply, plan, destroy 등)를 실행하고 결과를 검증합니다.
run "create_s3_bucket" {
command = apply
variables {
bucket_name = "test-bucket-1234"
}
assert {
condition = aws_s3_bucket.main.bucket == "test-bucket-1234"
error_message = "S3 버킷 이름이 일치하지 않습니다"
}
}
run 블록의 주요 속성
command: 실행할 Terraform 명령어 (apply,plan,destroy)variables: 테스트에 사용할 변수module: 테스트할 모듈 지정providers: 프로바이더 매핑assert: 조건 검증 블록expect_failures: 예상되는 오류 조건
어설션(Assertions)
assert 블록을 사용하여 인프라 동작을 검증합니다.
run "test_outputs" {
command = apply
assert {
condition = output.vpc_id != ""
error_message = "VPC ID가 비어 있습니다"
}
assert {
condition = length(module.vpc.public_subnets) >= 2
error_message = "최소 2개의 퍼블릭 서브넷이 필요합니다"
}
}
프로바이더 모킹(Mocking)
실제 클라우드 리소스를 생성하지 않고 테스트하려면 프로바이더를 모킹합니다.
provider "aws" {
mock = true
# 모킹된 프로바이더 구성
mock_data {
# 특정 리소스 모킹
}
}
데이터 소스 모킹
provider "aws" {
mock = true
data "aws_ami" "ubuntu" {
mock_id = "ami-12345678"
}
}
조건부 테스트 (Custom Conditions)
사용자 정의 조건을 사용하여 사전 조건(precondition) 및 사후 조건(postcondition)을 검증합니다.
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
lifecycle {
precondition {
condition = var.instance_type != "t2.micro"
error_message = "프로덕션 환경에서는 t2.micro를 사용할 수 없습니다"
}
}
}
테스트 실행
로컬 실행
terraform test
특정 테스트 파일 실행
terraform test -filter="network.tftest.hcl"
자세한 출력 보기
terraform test -verbose
Terraform Cloud/Enterprise 연동
Terraform Cloud에서도 테스트를 실행할 수 있습니다.
# terraform.tfc.hcl
resource "tfe_workspace" "test" {
name = "infrastructure-test"
organization = "my-org"
execution_mode = "remote"
}
모범 사례
- 단위 테스트 작성: 각 모듈의 개별 동작을 검증하는 작은 테스트 작성
- 통합 테스트: 여러 모듈이 함께 동작하는 시나리오 테스트
- 환경 분리: development, staging, production 환경별로 다른 테스트 실행
- CI/CD 통합: GitHub Actions, GitLab CI, Jenkins 등에서
terraform test자동 실행
GitHub Actions 예시
name: Terraform Test
on:
push:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: hashicorp/setup-terraform@v2
- run: terraform init
- run: terraform test
문제 해결
일반적인 오류
| 오류 | 설명 | 해결 방법 |
|---|---|---|
No test files found | 테스트 파일을 찾을 수 없음 | .tftest.hcl 확장자 확인 |
Assertion failed | 어설션 조건 실패 | 조건 및 오류 메시지 확인 |
Provider not mocked | 프로바이더가 모킹되지 않음 | mock = true 설정 확인 |
Module not found | 모듈 경로 오류 | 소스 경로 확인 |
디버깅 팁
TF_LOG=debug환경 변수로 상세 로그 확인terraform console로 표현식 평가terraform validate로 구성 파일 구문 검증