terraform-expert
Writes safe, modular, idiomatic Terraform - remote state layout, module structure, plan-review discipline, version pinning, and blast-radius control. Use when someone asks "structure my Terraform repo", "how should I split state between environments", "terraform plan wants to destroy and recreate my database", "should I use count or for_each", or "how do I import existing infrastructure". Do NOT use for CI pipeline authoring in GitHub Actions - use github-actions instead; for Kubernetes manifests the infrastructure hosts, use kubernetes-basics; for managing app secrets outside IaC, use secrets-hygiene.
- License 许可
- MIT
- 最近更新
- 2026-10-14
- Stars
- ★ 25
- Forks
- 3
01 前言 Front Matter
- name
- terraform-expert
- metadata
- { "title": "Terraform Expert" }
- description
- Writes safe, modular, idiomatic Terraform - remote state layout, module structure, plan-review discipline, version pinning, and blast-radius control. Use when someone asks "structure my Terraform repo", "how should I split state between environments", "terraform plan wants to destroy and recreate my database", "should I use count or for_each", or "how do I import existing infrastructure". Do NOT use for CI pipeline authoring in GitHub Actions - use github-actions instead; for Kubernetes manifests the infrastructure hosts, use kubernetes-basics; for managing app secrets outside IaC, use secrets-hygiene.
03 SKILL.md 正文
Terraform Expert
The costly failure mode in Terraform is not syntax - it is an unreviewed apply that destroys a production database because a rename read as destroy-and-recreate, or two engineers corrupting shared state because it lived on a laptop. This skill structures Terraform so every change is a reviewed plan with a known blast radius, and state is a locked, encrypted, per-environment artifact.
Operating procedure
State comes first because everything else is recoverable from code; state is not.
Step 1: Gather inputs
- Cloud and providers in play, and whether infrastructure already exists (import path) or is greenfield.
- Environments - dev/staging/prod at minimum? Any per-region splits?
- Team size and apply model - local applies, CI-driven, or Terraform Cloud? Default for more than one engineer: CI-driven with plan output posted to the PR.
- Criticality tiers - which resources are irreplaceable (databases, DNS zones, KMS keys)? These get
prevent_destroy.
Step 2: Set up state before writing resources
- Remote backend always - S3 + DynamoDB locking, GCS, or Terraform Cloud. Local state for shared infrastructure guarantees eventual corruption or loss.
- One state file per environment. Never share state across environments: a bad apply in dev must be physically unable to touch prod.
- State stores secrets and all attribute values in plaintext - encrypt the backend at rest and restrict read access as tightly as the secrets it holds.
- Never edit state by hand. Refactors use
terraform state mv; adopting existing infrastructure usesimport(or import blocks). A hand-edited state file diverges from reality silently.
Step 3: Lay out the repository
modules/ # reusable building blocks, no env-specific values
vpc/
main.tf # resources
variables.tf # typed inputs with validation
outputs.tf # what consumers may depend on
ecs-service/
...
environments/ # thin per-env roots - wiring only
dev/
main.tf # module calls + env values
backend.tf # this env's state config
terraform.tfvars
staging/
prod/
Rules the skeleton encodes:
- Environments are thin: they call modules and pass variables. If an environment root contains a raw
resourceblock, that resource belongs in a module. - A module hardcodes zero environment values; everything env-specific arrives via
variables.tf. - Modules expose only deliberate
outputs.tf- consumers depending on undeclared internals break on refactor.
Step 4: Write idiomatic resources
variable "instance_count" {
type = number
default = 2
validation {
condition = var.instance_count > 0
error_message = "instance_count must be positive."
}
}
resource "aws_instance" "app" {
for_each = var.instances # stable keys, not count indexes
instance_type = each.value.type
tags = merge(local.common_tags, { Name = "app-${each.key}" })
}
for_eachovercountwhenever items have stable identities. Withcount, deleting item 0 renumbers every following item and Terraform destroys and recreates all of them.- Tag everything through one
common_tagslocal - untagged resources are unattributable in the bill and invisible to cleanup. - Mark sensitive outputs
sensitive = true. - Secrets come from a secrets manager via data sources; never hardcode them (they land in state and git either way, but hardcoding puts them in both).
Step 5: Pin versions and enforce plan review
- Pin providers and modules with
~>constraints and commit.terraform.lock.hcl. An unpinned provider means every teammate and CI run can resolve different code. - Every apply is preceded by a
terraform planreviewed by a human - in a PR for teams. The review question is always: does the plan contain anydestroyorreplaceyou did not intend? lifecycle { prevent_destroy = true }on every Step 1 irreplaceable resource. It turns a catastrophic apply into an explicit error.
Step 6: Operate - upgrades, drift, blast radius
- Provider upgrades: one minor version at a time, read the upgrade guide, plan in dev first. A plan full of forced replacements after a bump means stop and read, not apply.
- Drift: run plan on a schedule (daily in CI is a reasonable default); reconcile manual console changes back into code or revert them. Unreconciled drift compounds until plans become unreadable.
- Blast radius: when a single state's plan routinely exceeds a few hundred resources or takes many minutes, split it into independently-applied stacks (networking / data / compute) connected by remote state outputs or data sources. Smaller states mean smaller worst-case applies.
Worked contrast
Bad - environment root that will drift from staging within a month:
# environments/prod/main.tf
resource "aws_instance" "app" { # raw resource in an env root
count = 3 # count: delete one, recreate the rest
ami = "ami-0abc123" # hardcoded, differs from staging by accident
instance_type = "m5.large"
}
Good - the same intent through the module contract:
# environments/prod/main.tf
module "app" {
source = "../../modules/app-service"
instances = { a = { type = "m5.large" }, b = { type = "m5.large" }, c = { type = "m5.large" } }
env = "prod"
}
Prod and staging now differ only in the values they pass, and the diff between them is reviewable in one screen.
Deliverable
Produce a Terraform setup containing: the remote backend configuration with locking and encryption per environment; the modules/ + environments/ skeleton above populated for the actual stack; pinned provider constraints and a committed lockfile; prevent_destroy on every named irreplaceable resource; and a documented plan-review workflow (who reviews, where plan output lands).
Do NOT
- Do not keep shared state locally or share one state file across environments - the failure is corruption or cross-env damage, and both are unrecoverable by git.
- Do not apply without a reviewed plan; the plan is the only thing standing between a rename and a destroyed database.
- Do not use
countfor collections with identity - removals renumber and recreate everything after them. - Do not hand-edit state; use
state mvandimport. - Do not leave providers unpinned or the lockfile uncommitted.
- Do not put raw resources in environment roots - that is how prod and staging quietly diverge.
Quality bar
terraform validateand a clean review ofplanpass in every environment.- No environment root contains a
resourceblock; no module contains an environment-specific literal. - Every irreplaceable resource carries
prevent_destroy; a test plan proves a rename does not schedule a replace on them. - Backend is remote, locked, encrypted; states are one-per-env.
- All providers pinned with
~>, lockfile committed.
Escalation
Route CI pipeline mechanics (plan-on-PR, apply-on-merge jobs) to github-actions, workload manifests to kubernetes-basics, and secret storage policy to secrets-hygiene. For compliance-audited infrastructure (SOC 2 change-management evidence), pair with soc2-evidence-helper.
04 同仓库更多 Skills
有氧运动计划
zone-2-cardio-plan
当有人要求制定稳态有氧训练计划、进行有氧基础训练或达到第二区间、安排轻松或耐力型的每周有氧训练、按心率区间训练,或提高静息心率、最大摄氧量或耐力时,可以使用此方案。该方案构建了一个包含训练计划结构、训练方式选择和进度安排的心率区间有氧训练模块。本方案仅提供一般健身指导,不构成医疗建议。请勿用于设计力量或举重训练计划(请使用力量训练计划)、高强度间歇训练 (HIIT) 或循环训练(请使用体能训练和 HIIT 计划),或灵活性/柔韧性训练(请使用灵活性训练计划)。
youtube-script-writer
Writes retention-engineered long-form YouTube scripts on a hook/body/payoff architecture - a first-30-seconds hook that survives the retention cliff, a beat-sheet body with mini-hooks and bridges, timed pattern interrupts, and a payoff that over-delivers - with B-roll and editing cues marked inline. Use when someone says "script my next video", "my retention graph dies at the start", "tighten this draft", or "outline a video on X". Do NOT use for the 3-second opener of TikTok, Reels, or Shorts - use video-hook-writer instead; do NOT use for spoken voiceover synced to on-screen tutorial actions - use narration-script instead; do NOT use for a sales demo built on a buyer's discovery notes - use demo-script instead; do NOT use to design the thumbnail and title - use thumbnail-concept instead.
win-back-campaign
Designs segmented win-back email sequences for dormant users - dormancy tiers, a three-beat sequence with a single proportional incentive, and a suppression rule - and measures success by re-activation, not opens. Use when someone says "our users went quiet", "design a win-back campaign", "how do I re-engage lapsed customers", "should we email people who haven't logged in for months", or lifecycle messaging has stopped landing with a lapsed segment. Do NOT use for recovering an unfinished checkout - use abandoned-cart-sequence instead. Do NOT use for diagnosing and fixing why active customers cancel - use churn-reduction instead. Do NOT use for building always-on onboarding or nurture flows - use email-drip-builder instead.
wikipedia-style
Writes neutral, verifiable, encyclopedic prose following Wikipedia's core content policies and manual of style - NPOV, inline citations, notability-backed claims, and a strict ban on promotional language. Use when someone asks "write this like a Wikipedia article", "draft a Wikipedia page for this company or person", "make this neutral and encyclopedic", or "why does my article draft keep getting rejected". Do NOT use for persuasive or opinion writing - use op-ed-writer instead; for thesis-driven academic papers, use academic-essay; for verifying claims in existing text, use fact-checker.
whitepapers
Structures and writes authoritative B2B whitepapers - a standalone executive summary, a data-sized problem statement, methodology, evidence-driven findings, recommendations, and a soft call to action - flagging every claim that needs a real citation. Use when a marketer asks "write a whitepaper on this topic", "turn our research into a lead-gen asset", "make this credible enough for executives", or a draft reads like a product pitch instead of analysis. Do NOT use for customer-story-driven proof - use case-study-builder instead; for policy audiences, use policy-brief.
white-space-analysis
Finds unmet market gaps by ranking jobs-to-be-done on importance versus satisfaction, overlaying them against current solutions and workarounds, and validating that each gap is real, winnable, and worth winning. Use when someone asks "where are the gaps in this market", "what's underserved here", "where should we play next", or is hunting for product, feature, or market-entry opportunities. Do NOT use for profiling competitors and building battle cards - use competitive-intelligence instead; for putting a dollar figure on an identified opportunity - use market-sizing instead; for extracting jobs-to-be-done from raw customer interviews - use jtbd-extractor instead.