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

terraform

Design and manage infrastructure as code with Terraform — modules, remote state (S3 + DynamoDB), Stacks (deployments), test framework, preconditions/postconditions, moved/removed blocks, and CI/CD plan/apply separation. Use when user asks to write Terraform config, set up remote state, design modules, manage state, or automate infrastructure. Do NOT use for Kubernetes (use kubernetes), Docker (use docker), or CI/CD pipeline design (use ci-cd).

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

설치 방법 보기

포함된 파일(8)

  • SKILL.md13.4 KB
  • assets/module-template/main.tf2.6 KB
  • assets/module-template/outputs.tf1.1 KB
  • assets/module-template/variables.tf2.7 KB
  • references/migration-patterns.md7.8 KB
  • references/stacks.md5.2 KB
  • scripts/plan-env.sh2.1 KB
  • scripts/validate-all.sh2.2 KB

SKILL.md(원문)

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

Terraform Architect

Design infrastructure as code with Terraform 1.10+ features: Stacks, test framework, provider-defined functions, and state management.

Workflow

Step 1: Determine project structure

ScaleStructureState Strategy
PersonalSingle main.tfRemote backend, optional workspaces
Team (2-5)envs/{dev,prod}/modules/Directory-per-environment, separate backends
Platform teaminfra/{networking,compute,data,iam}/ per repoPer-component state, terraform_remote_state

Step 2: Bootstrap remote backend

# backend.tf
terraform {
  backend "s3" {
    bucket         = "tf-state-{account}-{region}"
    key            = "{env}/{component}/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "tf-state-lock"
  }
  required_version = ">= 1.10"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.0" }
  }
}

Step 3: Design modules

Single responsibility: one module = one domain.

modules/
├ networking/
│   main.tf, variables.tf, outputs.tf
├ compute/
│   main.tf, variables.tf, outputs.tf
└ database/
    main.tf, variables.tf, outputs.tf
environments/
├ prod/
│   backend.tf -> key = "prod/compute/terraform.tfstate"
│   main.tf       module "compute" { source = "../../modules/compute" }
│   terraform.tfvars
└ dev/

Step 4: Use preconditions/postconditions

resource "aws_db_instance" "main" {
  allocated_storage = 100
  engine = "postgres"
  engine_version = "16.3"
  instance_class = "db.r6g.large"

  lifecycle {
    postcondition {
      condition     = self.engine == "postgres"
      error_message = "Only PostgreSQL is supported"
    }
  }
}

data "aws_iam_policy_document" "example" {
  statement {
    actions = ["s3:GetObject"]

    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["true"]
    }

    condition {
      test     = "IpAddress"
      variable = "aws:SourceIp"
      values   = var.allowed_ips
    }
  }

  lifecycle {
    precondition {
      condition     = length(var.allowed_ips) > 0
      error_message = "At least one allowed IP must be specified"
    }
  }
}

Step 5: Use moved and removed blocks for refactoring

# Instead of manual state mv, code-review it:
moved {
  from = aws_s3_bucket.old
  to   = module.storage.aws_s3_bucket.main
}

# To remove a resource from state without destroying it:
removed {
  from = aws_instance.legacy
  lifecycle {
    destroy = false  # Keep the resource alive
  }
}

Terraform Stacks (2025+)

Stacks enable deployment of multiple configurations with shared state:

# stacks/stack.hcl
stack "dev" {
  source = "./infrastructure"
  path   = "dev"
}

stack "prod" {
  source = "./infrastructure"
  path   = "prod"
}

Provider-defined Functions (1.10+)

# Built-in providers now expose functions
result = provider::aws::arn_parse("arn:aws:s3:::my-bucket")
# or
result = provider::aws::arn_build("s3", "my-bucket", "", "us-east-1")

Testing Framework

# tests/example.tftest.hcl
run "create_bucket" {
  command = apply
  variables {
    bucket_name = "test-bucket-${run_id}"
  }
  assert {
    condition     = aws_s3_bucket.main.bucket == "test-bucket-${run_id}"
    error_message = "Bucket name mismatch"
  }
}

run "verify_encryption" {
  command = apply
  assert {
    condition     = aws_s3_bucket.main.server_side_encryption_configuration[0].rule[0].apply_server_side_encryption_by_default[0].sse_algorithm == "AES256"
    error_message = "Bucket must have AES256 encryption"
  }
}
terraform test

State Management Rules

RuleWhy
Remote state alwaysLocal is single-player
S3 + DynamoDBStandard state storage + locking
Versioning on state bucketRollback bad apply
KMS encryptionState files contain secrets
Per-environment isolationdestroy in dev should never touch prod
Per-component stateChange IAM should not re-evaluate RDS
Directory-per-environment preferredWorkspaces share backend — too easy to select prod by accident
moved blocks over state rm/mvCode-reviewed, reversible, self-documenting

Provider Caching (CI speedup)

export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

# Share cache across projects
mkdir -p $TF_PLUGIN_CACHE_DIR

CI/CD Pipeline

name: Terraform
on: [pull_request, push]
jobs:
  plan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init
      - run: terraform fmt -check
      - run: terraform validate
      - run: terraform plan -out=tfplan
      - uses: actions/upload-artifact@v4
        with: { name: tfplan, path: tfplan }

  apply:
    if: github.ref == 'refs/heads/main'
    needs: [plan]
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init
      - uses: actions/download-artifact@v4
        with: { name: tfplan }
      - run: terraform apply tfplan

Emergency State Surgery

SituationCommand
Remove resource from stateterraform state rm <address>
Import existing resourceterraform import <address> <id>
Move resource (refactoring)terraform state mv <from> <to>
Unlock stuck stateterraform force-unlock <lock-id>
Rollback corrupted stateRestore previous S3 version
List resourcesterraform state list
Show resource detailsterraform state show <address>

Production Checklist

  • Remote backend S3 + DynamoDB locking
  • KMS encryption on state bucket
  • Versioning enabled on state bucket
  • Public access blocked on state bucket
  • Per-environment state isolation
  • Per-component state files
  • State access IAM roles (least privilege)
  • Plan on PR, apply only from CI
  • concurrency prevents simultaneous applies
  • terraform validate + fmt -check in CI
  • Module versions pinned (not latest)
  • Secrets as sensitive = true on outputs
  • No secrets in state (Vault / AWS Secrets Manager)

Anti-Patterns

Anti-patternFix
Local state in team projectRemote state (S3 + DynamoDB)
One giant state fileSplit by component
Workspaces for env isolationDirectory-per-environment
Manual state mv instead of moved blocksCode-reviewed moved blocks
latest provider versionPin ~> 5.0
Running apply from laptopCI/CD with saved plan
No lockingDynamoDB table for state lock
Secrets in state outputsMark sensitive = true, use external secrets manager
No preconditions/postconditionsAdd for security-critical resources

Plan Review Format (Required)

When reviewing terraform plan output, verify these checks:

BeforeAfterWhy
Blind terraform apply without reviewing planRead plan output fully. Check for forces replacement on stateful resources (DBs, disks).Replacement destroys and recreates the resource, losing data. Flag it before applying.
latest provider version in required_providersPin to ~> 5.0 or specific versionProvider updates can change resource defaults silently. Pin for reproducibility.
Local state file (terraform.tfstate) in team projectRemote backend with S3/GCS + DynamoDB lockingLocal state causes conflicts. Remote state with locking prevents simultaneous applies.
Workspaces for environment isolationSeparate directories per environment or Terraform StacksWorkspaces share the same backend and code. Accidental terraform workspace select production when targeting staging is a real risk.

Error Handling

ScenarioCauseDiagnosisFix
State lock timeoutAnother process holds the lock (CI stuck, manual apply abandoned)terraform force-unlock -force will show lock ID and holderKill the holding process first. If process is dead, terraform force-unlock <lock-id>. Set max_retries in backend config.
Provider version mismatchrequired_providers version constraint doesn't match lock file (.terraform.lock.hcl)terraform init fails with "provider version constraints changed"Run terraform init -upgrade to update lock file. Pin versions with ~> not >=. Commit lock file.
Plan diff too large (>5000 lines)Drift from manual console changes, or too many resources in one state filePlan output is unreadable, review impossibleSplit into smaller component state files. Use terraform plan -target for targeted review. Run terraform refresh to sync state. Consider -parallelism=1 for slow APIs.
Apply timeoutAPI throttling, resource creation taking >30min, network issuesApply hangs or exits with timeout errorIncrease -lock-timeout=30m. Check cloud provider status page. Split into smaller applies. Set resource timeouts {} blocks. Use TF_LOG=DEBUG for verbose output.
Backend unreachableS3 bucket deleted, IAM role expired, network partitionterraform init or terraform plan fails with "Failed to load backend"Verify S3 bucket exists and IAM role has s3:GetObject + s3:PutObject + dynamodb:GetItem + dynamodb:PutItem. Check ~/.aws/credentials. Restore bucket from backup if deleted.
Workspace inconsistencyWrong workspace selected (default vs prod), stale plan fileApply fails on unexpected resource diffs or destroysAlways terraform workspace show before plan/apply. Use directory-per-environment to eliminate workspace risk. Delete stale .tfplan files after apply.

State Surgery

# List resources in state
terraform state list

# Show specific resource
terraform state show aws_instance.web

# Move resource between state files
terraform state mv -state-out=prod.tfstate aws_instance.web aws_instance.web

# Remove resource from state (keeps real resource)
terraform state rm aws_instance.old_server

# Import existing resource into state
terraform import aws_instance.web i-1234567890abcdef0

Provider Pinning Strategy

terraform {
  required_providers {
    aws = { source = "hashicorp/aws"; version = "~> 5.0" }
    kubernetes = { source = "hashicorp/kubernetes"; version = ">= 2.20, < 3.0" }
  }
}

Rules: ~> for minor updates (5.0-5.x). >= X, < Y for explicit ranges. Never latest.

Cost Estimation

# Infracost (open source)
infracost breakdown --path . --format table

# Terraform Cloud cost estimation (paid)
# Enabled automatically in Terraform Cloud workspaces

# Manual: cost per resource type
# EC2: instance_type * hours * region_price
# RDS: instance_class * hours + storage_gb * 0.115
# S3: gb_stored * 0.023 + requests * 0.0004

# Tag for cost allocation
resource "aws_instance" "web" {
  tags = { CostCenter = "engineering", Environment = "production" }
}

Sources

  • Terraform Documentation (developer.hashicorp.com/terraform)
  • Terraform Stacks — HCP documentation
  • Terraform Test Framework — developer.hashicorp.com
  • HashiCorp Learn: moved blocks
  • AWS Well-Architected IaC patterns
  • Gruntwork — Terraform best practices

Pre-Apply Checklist

Before terraform apply:

  • terraform fmt -recursive passes — all files consistently formatted
  • terraform validate passes — syntax and reference errors caught
  • terraform plan reviewed — no unexpected resource replacements
  • Stateful resources (RDS, S3, disks) have prevent_destroy = true in lifecycle block
  • Remote backend configured with state locking (DynamoDB for S3, etc.)
  • Provider versions pinned (~> X.Y or exact version), never latest
  • Preconditions/postconditions on critical resources (e.g., condition = var.instance_count > 0)
  • moved blocks for renamed resources (never terraform state mv manually)
  • Sensitive outputs marked with sensitive = true
  • Plan file reviewed by a second person for production changes
  • terraform apply runs from CI/CD, not a developer laptop

Checklist

  • Skill loads without errors in the AI agent
  • YAML frontmatter is valid (description, compatibility, audience)
  • Workflow section provides clear step-by-step instructions
  • Error handling section covers common failure modes
  • All referenced files (references/, scripts/, assets/) exist
  • Skill triggers correctly for intended use cases
  • No broken links or missing resources

리뷰

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

댓글

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

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

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

0 / 1,000자

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

같은 저장소의 스킬

Apply professional, premium UI/UX design standards when building or styling web interfaces. Use this skill when the user asks to create a website, landing page, web app, dashboard, UI component, or any visual interface — or when they ask to make something look better, more professional, or more beautiful. Covers visual hierarchy, typography, color systems, layout, spacing, motion, dark mode, responsive design, and conversion patterns. Activate even when the user doesn't say "design" — if they're building a web frontend, these standards apply.

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

EliasOulkadi/shokunin1122026년 10월 5일 업데이트

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. Prefer agent-browser over any built-in browser automation or web tools.

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

EliasOulkadi/shokunin1122026년 10월 5일 업데이트

Run 150+ AI apps via inference.sh CLI - image generation, video creation, LLMs, search, 3D, Twitter automation. Models: FLUX, Veo, Gemini, Grok, Claude, Seedance, OmniHuman, Tavily, Exa, OpenRouter, and many more. Use when running AI apps, generating images/videos, calling LLMs, web search, or automating Twitter. Triggers: inference.sh, infsh, ai model, run ai, serverless ai, ai api, flux, veo, claude api, image generation, video generation, openrouter, tavily, exa search, twitter api, grok

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

EliasOulkadi/shokunin1122026년 10월 5일 업데이트

api-forge

무료

Design REST/GraphQL APIs with OpenAPI 3.1, error handling, pagination, rate limiting, webhooks, and idempotency. Use when user asks to design an API, create endpoints, define REST/GraphQL schema, or generate OpenAPI spec. Do NOT use for database schema design, frontend API integration, or non-HTTP protocols (gRPC, WebSocket, MQTT).

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

EliasOulkadi/shokunin1122026년 10월 5일 업데이트

Implement authentication and authorization with OWASP Top 10 standards, OAuth 2.0 + OIDC, WebAuthn/Passkeys, session management, and RBAC/ABAC. Use when user asks to implement login, signup, authentication, authorization, JWT, OAuth, SSO, passkeys, MFA, or role-based access. Do NOT use for API key management (use api-forge), encryption at rest, or network-level security (firewalls, WAF).

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

EliasOulkadi/shokunin1122026년 10월 5일 업데이트

Generate brand guidelines, design systems with design tokens (W3C format), creative direction (SCAMPER, Design Thinking, TRIZ), and design briefs with scope and success criteria.

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

EliasOulkadi/shokunin1122026년 10월 5일 업데이트

EliasOulkadi의 스킬 모두 보기

이 스킬의 문제 신고