Community생산성 & 협업github.com

hashicorp/terraform-test

Terraform 테스트 작성 및 실행을 위한 종합 가이드입니다. 테스트 파일(.tftest.hcl) 생성, run 블록을 사용한 테스트 시나리오 작성, 어설션을 통한 인프라 동작 확인, 프로바이더 및 데이터 소스 모킹, 모듈 출력 및 리소스 구성 테스트, Terraform 테스트 구문 및 실행 문제 해결 시 사용하세요.

terraform-test란 무엇인가요?

이 스킬은 Terraform 테스트를 작성하고 실행하는 방법에 대한 포괄적인 안내를 제공합니다. 개발자는 `.tftest.hcl` 파일을 생성하여 인프라 코드의 동작을 검증할 수 있습니다. `run` 블록을 사용하여 테스트 시나리오를 정의하고, `assert` 문을 통해 리소스 속성, 출력 값, 조건 등을 확인합니다. 프로바이더와 데이터 소스를 모킹하여 외부 종속성 없이 모듈을 테스트할 수 있으며, 사용자 정의 조건(Custom Conditions)을 활용하여 사전 조건 및 사후 조건을 검증합니다. 또한, Terraform Cloud/Enterprise와의 연동을 지원하며, CI/CD 파이프라인에서 테스트를 자동화할 수 있도록 명령어와 모범 사례를 제공합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/hashicorp/agent-skills/tree/main/skills/terraform-test

Installed? Explore more 생산성 & 협업 skills: steipete/gemini, steipete/gh-issues, steipete/skill-creator · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

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"
}

모범 사례

  1. 단위 테스트 작성: 각 모듈의 개별 동작을 검증하는 작은 테스트 작성
  2. 통합 테스트: 여러 모듈이 함께 동작하는 시나리오 테스트
  3. 환경 분리: development, staging, production 환경별로 다른 테스트 실행
  4. 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로 구성 파일 구문 검증

참고 자료

Individual skills in this repo

This repo contains 15 individual skills — each has its own dedicated page.

hashicorp/aws-ami-builder

Build Amazon Machine Images (AMIs) with Packer using the amazon-ebs builder. Use when creating custom AMIs for EC2 instances.

hashicorp/azure-image-builder

Build Azure managed images and Azure Compute Gallery images with Packer. Use when creating custom images for Azure VMs.

hashicorp/azure-verified-modules

Azure Verified Modules (AVM) requirements and best practices for developing certified Azure Terraform modules. Use when creating or reviewing Azure modules that need AVM certification.

hashicorp/new-terraform-provider

Use this when scaffolding a new Terraform provider.

hashicorp/provider-actions

Implement Terraform Provider actions using the Plugin Framework. Use when developing imperative operations that execute at lifecycle events (before/after create, update, destroy).

hashicorp/provider-docs

Create, update, and review Terraform provider documentation for Terraform Registry using HashiCorp-recommended patterns, tfplugindocs templates, and schema descriptions. Use when adding or changing provider configuration, resources, data sources, ephemeral resources, list resources, functions, or guides; when validating generated docs; and when troubleshooting missing or incorrect Registry documentation.

hashicorp/provider-resources

Implement Terraform Provider resources and data sources using the Plugin Framework. Use when developing CRUD operations, schema design, state management, and acceptance testing for provider resources.

hashicorp/provider-test-patterns

Terraform provider acceptance test patterns using terraform-plugin-testing with the Plugin Framework. Covers test structure, TestCase/TestStep fields, ConfigStateChecks with custom statecheck.StateCheck implementations, plan checks, CompareValue for cross-step assertions, config helpers, import testing with ImportStateKind, sweepers, and scenario patterns (basic, update, disappears, validation, regression), and ephemeral resource testing with the echoprovider package. Use when writing, reviewing, or debugging provider acceptance tests, including questions about statecheck, plancheck, TestCheckFunc, CheckDestroy, ExpectError, import state verification, ephemeral resources, or how to structure test files.

hashicorp/push-to-registry

Push Packer build metadata to HCP Packer registry for tracking and managing image lifecycle. Use when integrating Packer builds with HCP Packer for version control and governance.

hashicorp/refactor-module

Transform monolithic Terraform configurations into reusable, maintainable modules following HashiCorp's module design principles and community best practices.

hashicorp/run-acceptance-tests

Guide for running acceptance tests for a Terraform provider. Use this when asked to run an acceptance test or to run a test with the prefix `TestAcc`.

hashicorp/terraform-search-import

Discover existing cloud resources using Terraform Search queries and bulk import them into Terraform management. Use when bringing unmanaged infrastructure under Terraform control, auditing cloud resources, or migrating to IaC.

hashicorp/terraform-stacks

Comprehensive guide for working with HashiCorp Terraform Stacks. Use when creating, modifying, or validating Terraform Stack configurations (.tfcomponent.hcl, .tfdeploy.hcl files), working with stack components and deployments from local modules, public registry, or private registry sources, managing multi-region or multi-environment infrastructure, or troubleshooting Terraform Stacks syntax and structure.

hashicorp/terraform-style-guide

Generate Terraform HCL code following HashiCorp's official style conventions and best practices. Use when writing, reviewing, or generating Terraform configurations.

hashicorp/windows-builder

Build Windows images with Packer using WinRM communicator and PowerShell provisioners. Use when creating Windows AMIs, Azure images, or VMware templates.

관련 스킬