본문으로 건너뛰기
cccskills
무료GitHub에 공개

terraform-best-practices

Quick reference for Terraform conventions including file organization, naming, modules, state, security, and anti-patterns. Use when writing or reviewing Terraform code.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구AWSTerraform

실행 점수 미검증

설치 방법 보기

포함된 파일(1)

  • SKILL.md6.5 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Terraform Best Practices — Quick Reference

File Organization

terraform/
  live/                    # Orchestration — providers, backend, module calls
    terraform.tf           # backend + provider (ONLY place for providers)
    variables.tf           # all input variables
    locals.tf              # computed values, remote state refs
    outputs.tf             # exported values
    {resource-group}.tf    # module invocations grouped by concern
  modules/{name}/          # Reusable — no providers, no hardcoded values
    main.tf                # locals, data sources
    variables.tf           # inputs with descriptions + types
    outputs.tf             # consumed values only
    versions.tf            # required_providers
    {resource}.tf          # one file per resource type
  envs/{env}/              # Per-environment config
    state.config           # backend partial config
    terraform.tfvars       # non-sensitive values
    secrets.tfvars         # sensitive values (gitignored)

Naming

ThingConventionExample
Resource prefix{project}-{service}-{env}acme-payments-prod
Variablessnake_caseinstance_class
Localssnake_casename_prefix
Outputssnake_caserepository_url
Resourcesthis (primary) or descriptiveaws_db_instance.this
Security groupsname_prefix (not name)"${local.name_prefix}-app-"
Files{resource-type}.tfrds.tf, sg.tf, ecr.tf
Moduleskebab-case directorymodules/ecs-service/
TagsPascalCase keysProject, Environment, ManagedBy

Module Patterns

Use modules from the c0x12c Terraform Registry. Each module source follows c0x12c/{name}/aws — see the registry for available modules and versions.

# Calling a registry module — always version-pin
module "database" {
  source  = "c0x12c/rds/aws"
  version = "~> 0.6.6"

  name       = "${local.name_prefix}-db"
  vpc_id     = local.vpc_id
  subnet_ids = local.private_subnet_ids
  tags       = local.common_tags
}

# Inside a module — no provider, explicit interface
# versions.tf
terraform {
  required_version = ">= 1.5.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

# variables.tf — every var has description + type
variable "name" {
  description = "Resource name prefix"
  type        = string
}

# outputs.tf — only what consumers need
output "endpoint" {
  description = "Connection endpoint"
  value       = aws_db_instance.this.endpoint
}

State Management

# Backend config — S3 + DynamoDB locking
terraform {
  backend "s3" {}
}

# envs/dev/state.config
bucket         = "{project}-terraform-state"
key            = "{service}/dev/terraform.tfstate"
region         = "us-east-1"
dynamodb_table = "{project}-terraform-locks"
encrypt        = true

# Init with partial config
# terraform init -backend-config=../envs/dev/state.config
# Remote state for cross-stack references
data "terraform_remote_state" "infra" {
  backend = "s3"
  config = {
    bucket = "{project}-terraform-state"
    key    = "infra/terraform.tfstate"
    region = var.region
  }
}

locals {
  vpc_id = data.terraform_remote_state.infra.outputs.vpc_id
}

Security Checklist

# Sensitive variables
variable "db_password" {
  type      = string
  sensitive = true
}

# S3 — block public, encrypt, version
module "s3" {
  versioning              = true
  server_side_encryption  = { sse_algorithm = "aws:kms" }
  block_public_access     = {
    block_public_acls       = true
    block_public_policy     = true
    ignore_public_acls      = true
    restrict_public_buckets = true
  }
}

# RDS — encrypt, private subnet, protect
resource "aws_db_instance" "this" {
  storage_encrypted   = true
  deletion_protection = var.env == "prod"
  publicly_accessible = false  # ALWAYS false
}

# Security groups — source SG, not CIDR
resource "aws_security_group_rule" "app_to_db" {
  source_security_group_id = aws_security_group.app.id  # not cidr_blocks
  from_port                = 5432
  to_port                  = 5432
}

# Default tags at provider level
provider "aws" {
  default_tags {
    tags = {
      Project     = var.project
      Service     = var.service
      Environment = var.env
      ManagedBy   = "terraform"
    }
  }
}

Common Anti-Patterns

# WRONG — provider in module
# modules/rds/main.tf
provider "aws" { region = "us-east-1" }  # NEVER in a module

# WRONG — no version pin
module "rds" {
  source = "git::https://github.com/{project}/terraform-modules.git//rds"
  # missing ?ref=vX.Y.Z
}

# WRONG — hardcoded values
resource "aws_s3_bucket" "assets" {
  bucket = "acme-prod-assets"  # use ${local.name_prefix}-assets
}

# WRONG — secrets in code
resource "aws_db_instance" "main" {
  password = "hunter2"  # use var.db_password (sensitive)
}

# WRONG — wildcard IAM
resource "aws_iam_policy" "app" {
  policy = jsonencode({
    Statement = [{ Action = "*", Resource = "*", Effect = "Allow" }]
  })
}

# WRONG — public database
resource "aws_db_instance" "main" {
  publicly_accessible = true  # NEVER for databases
}

# WRONG — no state locking
terraform {
  backend "s3" {
    # missing dynamodb_table for locking
  }
}

# WRONG — all resources in one file
# main.tf with 500+ lines of mixed RDS, S3, SQS, IAM...
# Split into rds.tf, s3.tf, sqs.tf, iam.tf

CI/CD Patterns

# Standard workflow
# PR: fmt check → validate → plan (comment on PR)
# Merge to main: init → plan → apply

# Key rules:
# - Never auto-apply on PR
# - Always post plan output as PR comment
# - Lock state during apply (DynamoDB)
# - Inject secrets via CI environment variables
# - Pin Terraform version in CI to match team

What to Avoid

  • Provider blocks in modules
  • Unpinned module versions
  • Hardcoded names, IDs, or account numbers
  • Secrets in .tf files or committed .tfvars
  • Wildcard IAM policies (* on *)
  • Public databases or caches
  • Missing encryption on storage
  • Monolithic files (split by resource type)
  • terraform import in automation (use import blocks)
  • Missing description on variables and outputs
  • Nested locals maps (keep flat)
  • count for conditional resources (use for_each with a set)

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Creates RPC-style endpoint following layered architecture (Controller → Manager → Repository). Use when creating new API endpoints or CRUD operations.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

c0x12c/ai-toolkit1092026년 6월 18일 업데이트

Write blog posts, guides, tutorials, and long-form content. Sounds like a real person, not AI. Use when the user wants polished written content.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

c0x12c/ai-toolkit1092026년 6월 18일 업데이트

Design RPC-style APIs with layered architecture (Controller → Manager → Repository). Use when creating new API endpoints, designing API contracts, or reviewing API patterns.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

c0x12c/ai-toolkit1092026년 6월 18일 업데이트

Run a structured brainstorm session for startup ideas. Takes a theme or problem and generates ideas with quick gut-checks. Use when the user wants to explore a space or generate new ideas.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

c0x12c/ai-toolkit1092026년 6월 18일 업데이트

Run real browser QA with Playwright. Use when testing a frontend feature, verifying UI before PR, smoke testing after deploy, or investigating reported visual bugs.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

c0x12c/ai-toolkit1092026년 6월 18일 업데이트

CI/CD pipeline patterns for GitHub Actions, PR automation, and deployment workflows. Use when setting up CI, fixing broken pipelines, automating PR checks, or configuring deployment.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

c0x12c/ai-toolkit1092026년 6월 18일 업데이트

c0x12c의 스킬 모두 보기

이 스킬의 문제 신고