[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76XPM66C4KARK0S01M6WEX1":3,"skill-same:01M76XPM66C4KARK0S01M6WEX1":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M76XPM66C4KARK0S01M6WEX1","Terraform & Infrastructure as Code Production Engineering",null,"Complete Terraform & IaC production methodology — project structure, module design, state management, multi-environment deployment, security hardening, testing, CI\u002FCD pipelines, cost optimization, and drift management. Use when designing infrastructure, writing Terraform, reviewing IaC, or managing cloud environments.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fa\u002Fafrexai-terraform-production\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: Terraform & Infrastructure as Code Production Engineering\ndescription: Complete Terraform & IaC production methodology — project structure, module design, state management, multi-environment deployment, security hardening, testing, CI\u002FCD pipelines, cost optimization, and drift management. Use when designing infrastructure, writing Terraform, reviewing IaC, or managing cloud environments.\n---\n\n# Terraform & Infrastructure as Code Production Engineering\n\nComplete 14-phase system for production-grade infrastructure as code. Zero dependencies — works with any cloud provider and any Terraform version.\n\n---\n\n## Phase 1: Quick Health Check\n\nRun this 8-signal triage on any Terraform project:\n\n| # | Signal | ✅ Healthy | 🔴 Fix Now |\n|---|--------|-----------|-----------|\n| 1 | Remote state backend | S3\u002FGCS\u002FAzure Blob with locking | Local state or no locking |\n| 2 | State encryption | Encrypted at rest + restricted access | Plain state, wide access |\n| 3 | Module pinning | All modules version-pinned | Unpinned or `ref=main` |\n| 4 | Provider pinning | `required_providers` with `~>` constraints | No version constraints |\n| 5 | Separate environments | Isolated state per env (dev\u002Fstaging\u002Fprod) | Shared state or workspaces-as-envs |\n| 6 | Plan before apply | CI runs `plan`, human approves, CI runs `apply` | Local `apply` without review |\n| 7 | Secrets management | No secrets in `.tf` files; vault\u002FSSM\u002Fsecrets manager | Hardcoded secrets anywhere |\n| 8 | Drift detection | Scheduled drift checks (weekly minimum) | No drift monitoring |\n\n**Score: \u002F16** (2 per signal). Below 10 = stop and fix foundations first.\n\n---\n\n## Phase 2: Project Structure\n\n### Recommended Layout\n\n```\ninfrastructure\u002F\n├── modules\u002F                    # Reusable modules (internal registry)\n│   ├── networking\u002F\n│   │   ├── main.tf\n│   │   ├── variables.tf\n│   │   ├── outputs.tf\n│   │   ├── versions.tf\n│   │   └── README.md\n│   ├── compute\u002F\n│   ├── database\u002F\n│   └── monitoring\u002F\n├── environments\u002F               # Environment-specific configs\n│   ├── dev\u002F\n│   │   ├── main.tf            # Module calls with dev params\n│   │   ├── backend.tf         # Dev state backend\n│   │   ├── terraform.tfvars   # Dev variable values\n│   │   └── versions.tf\n│   ├── staging\u002F\n│   └── prod\u002F\n├── global\u002F                     # Shared resources (IAM, DNS, etc.)\n│   ├── iam\u002F\n│   ├── dns\u002F\n│   └── networking\u002F\n├── scripts\u002F                    # Helper scripts (import, migration)\n├── policies\u002F                   # OPA\u002FSentinel policies\n└── .github\u002Fworkflows\u002F          # CI\u002FCD pipelines\n```\n\n### 7 Architecture Rules\n\n1. **One module = one responsibility** — networking module doesn't create compute\n2. **Environments are thin** — they call modules with different parameters, not duplicate code\n3. **State isolation** — separate state file per environment AND per logical group (networking vs compute)\n4. **No hardcoded values in modules** — everything is a variable with sensible defaults\n5. **Outputs are your API** — if another module\u002Fteam needs a value, it's an output\n6. **README per module** — inputs, outputs, usage example, dependencies\n7. **`.terraform.lock.hcl` committed** — reproducible provider versions\n\n### File Naming Convention\n\n| File | Purpose |\n|------|---------|\n| `main.tf` | Primary resource definitions |\n| `variables.tf` | All input variables |\n| `outputs.tf` | All outputs |\n| `versions.tf` | `terraform` and `required_providers` blocks |\n| `backend.tf` | State backend configuration |\n| `locals.tf` | Local values and computed expressions |\n| `data.tf` | Data sources |\n| `providers.tf` | Provider configuration (if complex) |\n\n---\n\n## Phase 3: State Management\n\n### Remote Backend Setup (AWS Example)\n\n```hcl\n# backend.tf\nterraform {\n  backend \"s3\" {\n    bucket         = \"company-terraform-state\"\n    key            = \"environments\u002Fprod\u002Fnetworking\u002Fterraform.tfstate\"\n    region         = \"us-east-1\"\n    encrypt        = true\n    dynamodb_table = \"terraform-state-lock\"\n    kms_key_id     = \"alias\u002Fterraform-state\"\n  }\n}\n```\n\n### State Key Strategy\n\n```\n{org}\u002F{environment}\u002F{component}\u002Fterraform.tfstate\n```\n\nExamples:\n- `acme\u002Fprod\u002Fnetworking\u002Fterraform.tfstate`\n- `acme\u002Fprod\u002Fcompute\u002Fterraform.tfstate`\n- `acme\u002Fglobal\u002Fiam\u002Fterraform.tfstate`\n\n### State Operations Safety Rules\n\n| Operation | Risk | Safe Approach |\n|-----------|------|---------------|\n| `terraform state mv` | Medium | Plan after to verify no changes |\n| `terraform state rm` | High | Only to adopt resource elsewhere |\n| `terraform import` | Medium | Write config first, import, plan to verify |\n| `terraform state pull` | Low | For inspection only |\n| `terraform state push` | CRITICAL | Almost never — breaks consistency |\n| `moved` block | Low | Preferred over `state mv` — in config, reviewable |\n\n### 6 State Rules\n\n1. **Never edit state JSON manually** — use CLI commands only\n2. **Never share state across environments** — separate backends per env\n3. **Always enable locking** — DynamoDB (AWS), Cloud Storage (GCP), Blob lease (Azure)\n4. **Enable versioning on state bucket** — rollback capability\n5. **Restrict state access** — only CI\u002FCD service accounts, not developers\n6. **State contains secrets** — treat state files as sensitive; encrypt at rest + in transit\n\n---\n\n## Phase 4: Module Design\n\n### Module Interface Template\n\n```hcl\n# variables.tf — Module inputs\nvariable \"name\" {\n  description = \"Name prefix for all resources\"\n  type        = string\n  validation {\n    condition     = can(regex(\"^[a-z][a-z0-9-]{2,28}[a-z0-9]$\", var.name))\n    error_message = \"Name must be 4-30 chars, lowercase alphanumeric + hyphens.\"\n  }\n}\n\nvariable \"environment\" {\n  description = \"Deployment environment\"\n  type        = string\n  validation {\n    condition     = contains([\"dev\", \"staging\", \"prod\"], var.environment)\n    error_message = \"Environment must be dev, staging, or prod.\"\n  }\n}\n\nvariable \"tags\" {\n  description = \"Common tags applied to all resources\"\n  type        = map(string)\n  default     = {}\n}\n```\n\n```hcl\n# outputs.tf — Module contract\noutput \"vpc_id\" {\n  description = \"ID of the created VPC\"\n  value       = aws_vpc.main.id\n}\n\noutput \"private_subnet_ids\" {\n  description = \"List of private subnet IDs\"\n  value       = aws_subnet.private[*].id\n}\n```\n\n### Module Composition Pattern\n\n```hcl\n# environments\u002Fprod\u002Fmain.tf\nmodule \"networking\" {\n  source      = \"..\u002F..\u002Fmodules\u002Fnetworking\"\n  name        = \"prod\"\n  environment = \"prod\"\n  vpc_cidr    = \"10.0.0.0\u002F16\"\n  azs         = [\"us-east-1a\", \"us-east-1b\", \"us-east-1c\"]\n  tags        = local.common_tags\n}\n\nmodule \"compute\" {\n  source             = \"..\u002F..\u002Fmodules\u002Fcompute\"\n  name               = \"prod\"\n  environment        = \"prod\"\n  vpc_id             = module.networking.vpc_id\n  private_subnet_ids = module.networking.private_subnet_ids\n  instance_type      = \"t3.large\"\n  min_size           = 3\n  max_size           = 10\n  tags               = local.common_tags\n}\n```\n\n### 8 Module Design Rules\n\n1. **Expose what's needed, hide what's not** — minimal variable surface\n2. **Use `for_each` over `count`** — stable resource addressing\n3. **Validate inputs** — `validation` blocks catch errors at plan time\n4. **Default to secure** — encryption on, public access off, least privilege\n5. **Version everything** — semver for modules, `~>` for providers\n6. **No provider config in modules** — providers configured in root only\n7. **Use `moved` blocks for refactoring** — not `state mv`\n8. **Test with examples** — `examples\u002F` directory with working configurations\n\n---\n\n## Phase 5: Multi-Environment Strategy\n\n### Environment Comparison\n\n| Aspect | Dev | Staging | Prod |\n|--------|-----|---------|------|\n| Instance sizes | Small\u002Fmicro | Match prod types | Right-sized |\n| Replica count | 1 | 2 | 3+ (HA) |\n| Multi-AZ | Optional | Yes | Yes |\n| Backup retention | 1 day | 7 days | 30+ days |\n| Monitoring | Basic | Full | Full + PagerDuty |\n| Auto-scaling | Off | On | On |\n| WAF\u002FShield | Off | On | On + Advanced |\n| State access | Dev team | DevOps | DevOps only |\n\n### Variable Hierarchy Pattern\n\n```hcl\n# modules\u002Fcompute\u002Fvariables.tf\nvariable \"instance_type\" {\n  type    = string\n  default = \"t3.micro\"  # Safe default\n}\n\nvariable \"min_size\" {\n  type    = number\n  default = 1\n}\n\nvariable \"enable_deletion_protection\" {\n  type    = bool\n  default = true  # Safe default — must explicitly disable for dev\n}\n```\n\n```hcl\n# environments\u002Fdev\u002Fterraform.tfvars\ninstance_type              = \"t3.micro\"\nmin_size                   = 1\nenable_deletion_protection = false\n\n# environments\u002Fprod\u002Fterraform.tfvars\ninstance_type              = \"t3.large\"\nmin_size                   = 3\nenable_deletion_protection = true\n```\n\n### Promotion Strategy\n\n```\ndev → staging → prod\n │       │        │\n │       │        └─ Manual approval required\n │       └─ Auto-apply after plan review\n └─ Auto-apply on merge to dev branch\n```\n\n---\n\n## Phase 6: Security Hardening\n\n### 15-Point Security Checklist\n\n**P0 — Mandatory:**\n- [ ] No secrets in `.tf` files, `.tfvars`, or state (use vault\u002FSSM\u002Fsecrets manager)\n- [ ] State backend encrypted at rest with customer-managed keys\n- [ ] State access restricted to CI\u002FCD service accounts only\n- [ ] `prevent_destroy` on critical resources (databases, S3 with data)\n- [ ] Provider credentials via environment variables or OIDC, never in config\n- [ ] `.gitignore` includes `*.tfvars` with secrets, `.terraform\u002F`, `*.tfstate*`\n\n**P1 — Required:**\n- [ ] OIDC for CI\u002FCD auth (no long-lived access keys)\n- [ ] Least-privilege IAM for Terraform service account\n- [ ] Security group rules explicit (no `0.0.0.0\u002F0` ingress except ALB on 443)\n- [ ] Encryption enabled on all data stores (RDS, S3, EBS, ElastiCache)\n- [ ] VPC flow logs enabled\n- [ ] CloudTrail\u002Faudit logging for all API calls\n\n**P2 — Recommended:**\n- [ ] OPA\u002FSentinel policies enforced in CI\n- [ ] `tfsec` or `checkov` in CI pipeline\n- [ ] Separate AWS accounts per environment (AWS Organizations)\n\n### Secrets Management Decision Tree\n\n```\nNeed a secret in Terraform?\n├── Runtime secret (app needs at runtime)\n│   └── Use AWS Secrets Manager \u002F HashiCorp Vault\n│       └── Reference via data source, pass ARN to app\n├── Terraform-time secret (provider needs it)\n│   └── Environment variable (TF_VAR_xxx) or OIDC\n└── Generated secret (Terraform creates it)\n    └── random_password resource → store in Secrets Manager\n        └── Mark output as sensitive = true\n```\n\n### OIDC Authentication (GitHub Actions → AWS)\n\n```hcl\n# No access keys needed\ndata \"aws_iam_openid_connect_provider\" \"github\" {\n  url = \"https:\u002F\u002Ftoken.actions.githubusercontent.com\"\n}\n\nresource \"aws_iam_role\" \"terraform_ci\" {\n  name = \"terraform-ci\"\n  assume_role_policy = jsonencode({\n    Version = \"2012-10-17\"\n    Statement = [{\n      Effect = \"Allow\"\n      Principal = { Federated = data.aws_iam_openid_connect_provider.github.arn }\n      Action = \"sts:AssumeRoleWithWebIdentity\"\n      Condition = {\n        StringEquals = {\n          \"token.actions.githubusercontent.com:aud\" = \"sts.amazonaws.com\"\n        }\n        StringLike = {\n          \"token.actions.githubusercontent.com:sub\" = \"repo:org\u002Finfra:*\"\n        }\n      }\n    }]\n  })\n}\n```\n\n---\n\n## Phase 7: Testing Strategy\n\n### 4-Level Test Pyramid\n\n| Level | Tool | What It Tests | When |\n|-------|------|---------------|------|\n| **Static** | `terraform validate`, `tflint`, `tfsec`, `checkov` | Syntax, best practices, security | Every commit |\n| **Plan** | `terraform plan` + policy checks | Expected changes, no surprises | Every PR |\n| **Contract** | `terratest` \u002F `tftest` (TF 1.6+) | Module inputs\u002Foutputs, behavior | PR + nightly |\n| **Integration** | `terratest` with real cloud | Actual infrastructure works | Nightly\u002Fweekly |\n\n### Native Terraform Test (TF 1.6+)\n\n```hcl\n# tests\u002Fnetworking.tftest.hcl\nrun \"creates_vpc_with_correct_cidr\" {\n  command = plan\n\n  variables {\n    name        = \"test\"\n    environment = \"dev\"\n    vpc_cidr    = \"10.0.0.0\u002F16\"\n    azs         = [\"us-east-1a\"]\n  }\n\n  assert {\n    condition     = aws_vpc.main.cidr_block == \"10.0.0.0\u002F16\"\n    error_message = \"VPC CIDR doesn't match input\"\n  }\n\n  assert {\n    condition     = aws_vpc.main.enable_dns_hostnames == true\n    error_message = \"DNS hostnames should be enabled\"\n  }\n}\n\nrun \"rejects_invalid_environment\" {\n  command = plan\n  expect_failures = [var.environment]\n\n  variables {\n    name        = \"test\"\n    environment = \"invalid\"\n    vpc_cidr    = \"10.0.0.0\u002F16\"\n    azs         = [\"us-east-1a\"]\n  }\n}\n```\n\n### Static Analysis CI Step\n\n```yaml\n- name: Terraform Lint & Security\n  run: |\n    terraform fmt -check -recursive\n    terraform validate\n    tflint --recursive\n    tfsec .\n    checkov -d . --framework terraform\n```\n\n### 7 Testing Rules\n\n1. **Static analysis on every commit** — catches 80% of issues for free\n2. **Plan review on every PR** — humans approve infrastructure changes\n3. **Native tests for modules** — `terraform test` is built-in, use it\n4. **Integration tests destroy after** — `defer cleanup` to avoid orphaned resources\n5. **Test in isolated account** — never test against production state\n6. **Pin test dependencies** — terratest Go modules, provider versions\n7. **Cost estimation in CI** — `infracost` to catch expensive surprises\n\n---\n\n## Phase 8: CI\u002FCD Pipeline\n\n### GitHub Actions Pipeline\n\n```yaml\nname: Terraform\non:\n  pull_request:\n    paths: ['infrastructure\u002F**']\n  push:\n    branches: [main]\n    paths: ['infrastructure\u002F**']\n\npermissions:\n  id-token: write    # OIDC\n  contents: read\n  pull-requests: write  # PR comments\n\njobs:\n  validate:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: hashicorp\u002Fsetup-terraform@v3\n        with:\n          terraform_version: \"1.7.x\"\n      - run: terraform fmt -check -recursive\n      - run: terraform init -backend=false\n      - run: terraform validate\n      - run: tflint --recursive\n      - run: tfsec . --soft-fail\n\n  plan:\n    needs: validate\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        environment: [dev, staging, prod]\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: aws-actions\u002Fconfigure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role\u002Fterraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp\u002Fsetup-terraform@v3\n      - working-directory: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\n        run: |\n          terraform init\n          terraform plan -out=tfplan -no-color\n      - uses: actions\u002Fupload-artifact@v4\n        with:\n          name: tfplan-${{ matrix.environment }}\n          path: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\u002Ftfplan\n\n  apply:\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    needs: plan\n    runs-on: ubuntu-latest\n    environment: production  # Requires approval\n    strategy:\n      matrix:\n        environment: [dev, staging, prod]\n      max-parallel: 1  # Sequential: dev → staging → prod\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: aws-actions\u002Fconfigure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role\u002Fterraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp\u002Fsetup-terraform@v3\n      - uses: actions\u002Fdownload-artifact@v4\n        with:\n          name: tfplan-${{ matrix.environment }}\n          path: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\n      - working-directory: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\n        run: terraform apply tfplan\n```\n\n### CI\u002FCD Rules\n\n1. **Never `apply` from local machines** — CI\u002FCD only\n2. **Plan artifact = apply input** — same plan that was reviewed gets applied\n3. **Sequential environment promotion** — dev → staging → prod, not parallel\n4. **Production requires approval** — GitHub Environment protection rules\n5. **Drift detection on schedule** — weekly `plan` to detect manual changes\n6. **Cost estimation on PR** — Infracost or similar\n\n---\n\n## Phase 9: Resource Patterns\n\n### Tagging Strategy\n\n```hcl\nlocals {\n  common_tags = {\n    Project     = var.project_name\n    Environment = var.environment\n    ManagedBy   = \"terraform\"\n    Team        = var.team\n    CostCenter  = var.cost_center\n    Repository  = \"github.com\u002Forg\u002Finfrastructure\"\n  }\n}\n\n# Apply to all resources\nresource \"aws_instance\" \"app\" {\n  # ...\n  tags = merge(local.common_tags, {\n    Name = \"${var.name}-app\"\n    Role = \"application\"\n  })\n}\n```\n\n### Naming Convention\n\n```\n{project}-{environment}-{component}-{qualifier}\n```\n\nExamples: `acme-prod-vpc-main`, `acme-staging-rds-primary`, `acme-prod-alb-api`\n\n### Common Patterns\n\n**Conditional Resource Creation:**\n```hcl\nresource \"aws_cloudwatch_metric_alarm\" \"cpu\" {\n  count = var.environment == \"prod\" ? 1 : 0\n  # Only create alarms in prod\n}\n```\n\n**Dynamic Blocks:**\n```hcl\nresource \"aws_security_group\" \"app\" {\n  name   = \"${var.name}-app\"\n  vpc_id = var.vpc_id\n\n  dynamic \"ingress\" {\n    for_each = var.ingress_rules\n    content {\n      from_port   = ingress.value.port\n      to_port     = ingress.value.port\n      protocol    = \"tcp\"\n      cidr_blocks = ingress.value.cidrs\n      description = ingress.value.description\n    }\n  }\n}\n```\n\n**Data Source for Cross-Stack References:**\n```hcl\n# Instead of hardcoding VPC ID\ndata \"terraform_remote_state\" \"networking\" {\n  backend = \"s3\"\n  config = {\n    bucket = \"company-terraform-state\"\n    key    = \"environments\u002Fprod\u002Fnetworking\u002Fterraform.tfstate\"\n    region = \"us-east-1\"\n  }\n}\n\n# Use: data.terraform_remote_state.networking.outputs.vpc_id\n```\n\n---\n\n## Phase 10: Drift Management\n\n### Drift Detection Schedule\n\n```yaml\n# .github\u002Fworkflows\u002Fdrift-detection.yml\nname: Drift Detection\non:\n  schedule:\n    - cron: '0 8 * * 1'  # Weekly Monday 8 AM UTC\n\njobs:\n  detect:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        environment: [dev, staging, prod]\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: aws-actions\u002Fconfigure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role\u002Fterraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp\u002Fsetup-terraform@v3\n      - working-directory: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\n        run: |\n          terraform init\n          terraform plan -detailed-exitcode -no-color 2>&1 | tee plan.txt\n          EXIT_CODE=$?\n          if [ $EXIT_CODE -eq 2 ]; then\n            echo \"::warning::Drift detected in ${{ matrix.environment }}\"\n            # Send Slack alert\n          fi\n```\n\n### Drift Response Playbook\n\n| Drift Type | Response |\n|-----------|----------|\n| Manual console change (cosmetic) | Import or update config to match |\n| Manual console change (critical) | Investigate who\u002Fwhy, then align |\n| Auto-scaling \u002F ASG changes | Expected — use `ignore_changes` for dynamic attributes |\n| AWS service updates | Update provider version, review changelog |\n| Security group modified manually | 🚨 Security incident — investigate immediately |\n\n### `ignore_changes` Decision Guide\n\nUse `ignore_changes` ONLY for:\n- Attributes modified by the application at runtime (e.g., ASG desired count)\n- Tags managed by external systems (e.g., AWS Backup tags)\n- Attributes that drift due to API behavior (e.g., default security group rules)\n\n**Never `ignore_changes` for:**\n- Security configurations\n- Network rules\n- IAM policies\n- Encryption settings\n\n---\n\n## Phase 11: Cost Optimization\n\n### Infracost in CI\n\n```yaml\n- name: Infracost\n  run: |\n    infracost breakdown --path infrastructure\u002Fenvironments\u002Fprod\u002F \\\n      --format json --out-file infracost.json\n    infracost output --path infracost.json --format github-comment \\\n      --out-file comment.md\n    # Post as PR comment\n```\n\n### Cost Optimization Checklist\n\n| Strategy | Savings | Implementation |\n|----------|---------|----------------|\n| Reserved Instances \u002F Savings Plans | 30-60% | Annual commitment for stable workloads |\n| Right-sizing | 20-40% | Monitor CPU\u002Fmemory, downsize over-provisioned |\n| Spot\u002FPreemptible for non-critical | 60-90% | Batch jobs, dev environments |\n| S3 lifecycle policies | 20-50% storage | Transition to IA → Glacier → delete |\n| NAT Gateway alternatives | $30-100\u002Fmo per GW | NAT instances for dev, VPC endpoints |\n| Dev environment scheduling | 60-70% | Destroy nights\u002Fweekends, recreate on demand |\n| Unused resource cleanup | Variable | Tag with TTL, auto-delete untagged after 7 days |\n\n### Tagging for Cost Allocation\n\nRequired cost tags (enforce via policy):\n- `CostCenter` — maps to business unit\n- `Environment` — dev\u002Fstaging\u002Fprod\n- `Project` — which project owns this\n- `Team` — responsible team\n- `ManagedBy` — terraform\u002Fmanual\u002Fother\n\n---\n\n## Phase 12: Advanced Patterns\n\n### Terragrunt for DRY Environments\n\nWhen you have 5+ environments with identical module structures, Terragrunt eliminates repetition:\n\n```hcl\n# terragrunt.hcl (root)\nremote_state {\n  backend = \"s3\"\n  generate = { path = \"backend.tf\", if_exists = \"overwrite_terragrunt\" }\n  config = {\n    bucket         = \"company-terraform-state\"\n    key            = \"${path_relative_to_include()}\u002Fterraform.tfstate\"\n    region         = \"us-east-1\"\n    encrypt        = true\n    dynamodb_table = \"terraform-state-lock\"\n  }\n}\n```\n\n### Import Block (TF 1.5+)\n\n```hcl\n# Declarative import — reviewable in PR\nimport {\n  to = aws_s3_bucket.existing\n  id = \"my-existing-bucket\"\n}\n\nresource \"aws_s3_bucket\" \"existing\" {\n  bucket = \"my-existing-bucket\"\n  # Write config to match existing resource\n}\n```\n\n### Provider Aliases for Multi-Region\n\n```hcl\nprovider \"aws\" {\n  region = \"us-east-1\"\n}\n\nprovider \"aws\" {\n  alias  = \"eu\"\n  region = \"eu-west-1\"\n}\n\nmodule \"eu_networking\" {\n  source = \"..\u002F..\u002Fmodules\u002Fnetworking\"\n  providers = { aws = aws.eu }\n  # ...\n}\n```\n\n### `moved` Block for Refactoring\n\n```hcl\n# Rename without destroy+create\nmoved {\n  from = aws_instance.app\n  to   = aws_instance.application\n}\n\n# Move into module\nmoved {\n  from = aws_instance.app\n  to   = module.compute.aws_instance.app\n}\n```\n\n---\n\n## Phase 13: Disaster Recovery & Migration\n\n### State Recovery\n\n```bash\n# Enable versioning on state bucket (BEFORE you need it)\naws s3api put-bucket-versioning \\\n  --bucket company-terraform-state \\\n  --versioning-configuration Status=Enabled\n\n# List state versions\naws s3api list-object-versions \\\n  --bucket company-terraform-state \\\n  --prefix environments\u002Fprod\u002Fnetworking\u002Fterraform.tfstate\n\n# Restore previous version\naws s3api get-object \\\n  --bucket company-terraform-state \\\n  --key environments\u002Fprod\u002Fnetworking\u002Fterraform.tfstate \\\n  --version-id \"versionId123\" \\\n  restored-state.tfstate\n```\n\n### Migration Checklist (Moving Between Backends)\n\n1. [ ] `terraform state pull > backup.tfstate` — backup current state\n2. [ ] Update `backend.tf` with new backend config\n3. [ ] `terraform init -migrate-state` — Terraform copies state\n4. [ ] `terraform plan` — verify no changes (state matches)\n5. [ ] Test apply on non-critical resource\n6. [ ] Delete old state after verification period (7 days)\n\n### Breaking Changes Protocol\n\nWhen upgrading major Terraform or provider versions:\n1. Read changelog for breaking changes\n2. Test upgrade in dev first\n3. Update `.terraform.lock.hcl`\n4. Run `terraform plan` in all environments\n5. Apply dev → staging → prod with 24h gaps\n\n---\n\n## Phase 14: Quality Scoring\n\n### 100-Point Terraform Quality Rubric\n\n| Dimension | Weight | Score Range |\n|-----------|--------|-------------|\n| State management | 20% | 0-20 |\n| Security posture | 20% | 0-20 |\n| Module design | 15% | 0-15 |\n| Testing coverage | 15% | 0-15 |\n| CI\u002FCD automation | 10% | 0-10 |\n| Documentation | 10% | 0-10 |\n| Cost governance | 5% | 0-5 |\n| Drift management | 5% | 0-5 |\n\n**Scoring Guide:**\n- **90-100**: Production-grade, fully automated, battle-tested\n- **70-89**: Solid foundation, some gaps to address\n- **50-69**: Functional but risky — prioritize security and state management\n- **Below 50**: Stop deploying and fix fundamentals\n\n### 10 Terraform Commandments\n\n1. **Remote state with locking or don't start**\n2. **Never hardcode secrets — not in code, not in state if avoidable**\n3. **Plan is sacred — review every plan, apply only reviewed plans**\n4. **Modules are contracts — version them, test them, document them**\n5. **Environments are isolated — separate state, separate accounts ideally**\n6. **`for_each` over `count` — stable addressing saves you**\n7. **CI\u002FCD applies, humans don't — no local `terraform apply` in prod**\n8. **Tag everything — cost allocation, ownership, lifecycle**\n9. **Drift is a bug — detect it weekly, fix it immediately**\n10. **Upgrade deliberately — test in dev, read changelogs, lock versions**\n\n### 10 Common Mistakes\n\n| Mistake | Impact | Fix |\n|---------|--------|-----|\n| Local state for team projects | State conflicts, data loss | Remote backend day 1 |\n| Secrets in `.tfvars` committed to git | Credential exposure | Use vault\u002FSSM + env vars |\n| `count` for optional resources | Index shift on removal | `for_each` with conditional map |\n| Monolithic state file | Slow plans, blast radius | Split by component (networking\u002Fcompute\u002Fdata) |\n| No `prevent_destroy` on data stores | Accidental database deletion | Lifecycle rule on stateful resources |\n| Unpinned module versions | Breaking changes on init | Pin with `?ref=v1.2.3` or `version = \"~> 1.2\"` |\n| `terraform apply -auto-approve` in prod | Unreviewed changes | Plan artifact → human review → apply |\n| Using workspaces as environments | Shared state, shared blast radius | Separate directories + backends per env |\n| No cost estimation in CI | $10K surprise bills | Infracost or similar on every PR |\n| Manual changes \"just this once\" | Permanent drift | Always go through code, even for emergencies |\n\n---\n\n## Natural Language Commands\n\n- \"Review this Terraform code\" → Run Phase 1 health check + static analysis recommendations\n- \"Design infrastructure for [service]\" → Phase 2 structure + Phase 4 module design\n- \"Set up remote state\" → Phase 3 backend configuration\n- \"Create a module for [resource]\" → Phase 4 module template with variables\u002Foutputs\n- \"Compare environments\" → Phase 5 environment matrix\n- \"Security audit my Terraform\" → Phase 6 security checklist\n- \"Add tests to this module\" → Phase 7 native test examples\n- \"Set up CI\u002FCD for Terraform\" → Phase 8 GitHub Actions pipeline\n- \"Check for drift\" → Phase 10 drift detection setup\n- \"Estimate infrastructure costs\" → Phase 11 Infracost integration\n- \"Migrate state to new backend\" → Phase 13 migration checklist\n- \"Score this Terraform project\" → Phase 14 quality rubric\n\n---\n\n## ⚡ Level Up\n\nThis skill covers Terraform methodology and best practices. For industry-specific infrastructure patterns:\n\n- **SaaS Infrastructure** → [AfrexAI SaaS Context Pack ($47)](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n- **Fintech Compliance Infrastructure** → [AfrexAI Fintech Context Pack ($47)](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n- **Healthcare HIPAA Infrastructure** → [AfrexAI Healthcare Context Pack ($47)](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n\n## 🔗 More Free Skills by AfrexAI\n\n- `clawhub install afrexai-devops-engine` — Complete DevOps & Platform Engineering\n- `clawhub install afrexai-cybersecurity-engine` — Security Hardening & Compliance\n- `clawhub install afrexai-system-architect` — System Architecture Decision Frameworks\n- `clawhub install afrexai-api-architect` — API Design & Lifecycle Management\n- `clawhub install afrexai-cicd-engineering` — CI\u002FCD Pipeline Engineering\n\nBrowse all AfrexAI skills: [clawhub.com](https:\u002F\u002Fclawhub.com) → Search \"afrexai\"\n\nStorefront: [afrexai-cto.github.io\u002Fcontext-packs](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n","# Terraform & Infrastructure as Code Production Engineering\n\nComplete 14-phase system for production-grade infrastructure as code. Zero dependencies — works with any cloud provider and any Terraform version.\n\n---\n\n## Phase 1: Quick Health Check\n\nRun this 8-signal triage on any Terraform project:\n\n| # | Signal | ✅ Healthy | 🔴 Fix Now |\n|---|--------|-----------|-----------|\n| 1 | Remote state backend | S3\u002FGCS\u002FAzure Blob with locking | Local state or no locking |\n| 2 | State encryption | Encrypted at rest + restricted access | Plain state, wide access |\n| 3 | Module pinning | All modules version-pinned | Unpinned or `ref=main` |\n| 4 | Provider pinning | `required_providers` with `~>` constraints | No version constraints |\n| 5 | Separate environments | Isolated state per env (dev\u002Fstaging\u002Fprod) | Shared state or workspaces-as-envs |\n| 6 | Plan before apply | CI runs `plan`, human approves, CI runs `apply` | Local `apply` without review |\n| 7 | Secrets management | No secrets in `.tf` files; vault\u002FSSM\u002Fsecrets manager | Hardcoded secrets anywhere |\n| 8 | Drift detection | Scheduled drift checks (weekly minimum) | No drift monitoring |\n\n**Score: \u002F16** (2 per signal). Below 10 = stop and fix foundations first.\n\n---\n\n## Phase 2: Project Structure\n\n### Recommended Layout\n\n```\ninfrastructure\u002F\n├── modules\u002F                    # Reusable modules (internal registry)\n│   ├── networking\u002F\n│   │   ├── main.tf\n│   │   ├── variables.tf\n│   │   ├── outputs.tf\n│   │   ├── versions.tf\n│   │   └── README.md\n│   ├── compute\u002F\n│   ├── database\u002F\n│   └── monitoring\u002F\n├── environments\u002F               # Environment-specific configs\n│   ├── dev\u002F\n│   │   ├── main.tf            # Module calls with dev params\n│   │   ├── backend.tf         # Dev state backend\n│   │   ├── terraform.tfvars   # Dev variable values\n│   │   └── versions.tf\n│   ├── staging\u002F\n│   └── prod\u002F\n├── global\u002F                     # Shared resources (IAM, DNS, etc.)\n│   ├── iam\u002F\n│   ├── dns\u002F\n│   └── networking\u002F\n├── scripts\u002F                    # Helper scripts (import, migration)\n├── policies\u002F                   # OPA\u002FSentinel policies\n└── .github\u002Fworkflows\u002F          # CI\u002FCD pipelines\n```\n\n### 7 Architecture Rules\n\n1. **One module = one responsibility** — networking module doesn't create compute\n2. **Environments are thin** — they call modules with different parameters, not duplicate code\n3. **State isolation** — separate state file per environment AND per logical group (networking vs compute)\n4. **No hardcoded values in modules** — everything is a variable with sensible defaults\n5. **Outputs are your API** — if another module\u002Fteam needs a value, it's an output\n6. **README per module** — inputs, outputs, usage example, dependencies\n7. **`.terraform.lock.hcl` committed** — reproducible provider versions\n\n### File Naming Convention\n\n| File | Purpose |\n|------|---------|\n| `main.tf` | Primary resource definitions |\n| `variables.tf` | All input variables |\n| `outputs.tf` | All outputs |\n| `versions.tf` | `terraform` and `required_providers` blocks |\n| `backend.tf` | State backend configuration |\n| `locals.tf` | Local values and computed expressions |\n| `data.tf` | Data sources |\n| `providers.tf` | Provider configuration (if complex) |\n\n---\n\n## Phase 3: State Management\n\n### Remote Backend Setup (AWS Example)\n\n```hcl\n# backend.tf\nterraform {\n  backend \"s3\" {\n    bucket         = \"company-terraform-state\"\n    key            = \"environments\u002Fprod\u002Fnetworking\u002Fterraform.tfstate\"\n    region         = \"us-east-1\"\n    encrypt        = true\n    dynamodb_table = \"terraform-state-lock\"\n    kms_key_id     = \"alias\u002Fterraform-state\"\n  }\n}\n```\n\n### State Key Strategy\n\n```\n{org}\u002F{environment}\u002F{component}\u002Fterraform.tfstate\n```\n\nExamples:\n- `acme\u002Fprod\u002Fnetworking\u002Fterraform.tfstate`\n- `acme\u002Fprod\u002Fcompute\u002Fterraform.tfstate`\n- `acme\u002Fglobal\u002Fiam\u002Fterraform.tfstate`\n\n### State Operations Safety Rules\n\n| Operation | Risk | Safe Approach |\n|-----------|------|---------------|\n| `terraform state mv` | Medium | Plan after to verify no changes |\n| `terraform state rm` | High | Only to adopt resource elsewhere |\n| `terraform import` | Medium | Write config first, import, plan to verify |\n| `terraform state pull` | Low | For inspection only |\n| `terraform state push` | CRITICAL | Almost never — breaks consistency |\n| `moved` block | Low | Preferred over `state mv` — in config, reviewable |\n\n### 6 State Rules\n\n1. **Never edit state JSON manually** — use CLI commands only\n2. **Never share state across environments** — separate backends per env\n3. **Always enable locking** — DynamoDB (AWS), Cloud Storage (GCP), Blob lease (Azure)\n4. **Enable versioning on state bucket** — rollback capability\n5. **Restrict state access** — only CI\u002FCD service accounts, not developers\n6. **State contains secrets** — treat state files as sensitive; encrypt at rest + in transit\n\n---\n\n## Phase 4: Module Design\n\n### Module Interface Template\n\n```hcl\n# variables.tf — Module inputs\nvariable \"name\" {\n  description = \"Name prefix for all resources\"\n  type        = string\n  validation {\n    condition     = can(regex(\"^[a-z][a-z0-9-]{2,28}[a-z0-9]$\", var.name))\n    error_message = \"Name must be 4-30 chars, lowercase alphanumeric + hyphens.\"\n  }\n}\n\nvariable \"environment\" {\n  description = \"Deployment environment\"\n  type        = string\n  validation {\n    condition     = contains([\"dev\", \"staging\", \"prod\"], var.environment)\n    error_message = \"Environment must be dev, staging, or prod.\"\n  }\n}\n\nvariable \"tags\" {\n  description = \"Common tags applied to all resources\"\n  type        = map(string)\n  default     = {}\n}\n```\n\n```hcl\n# outputs.tf — Module contract\noutput \"vpc_id\" {\n  description = \"ID of the created VPC\"\n  value       = aws_vpc.main.id\n}\n\noutput \"private_subnet_ids\" {\n  description = \"List of private subnet IDs\"\n  value       = aws_subnet.private[*].id\n}\n```\n\n### Module Composition Pattern\n\n```hcl\n# environments\u002Fprod\u002Fmain.tf\nmodule \"networking\" {\n  source      = \"..\u002F..\u002Fmodules\u002Fnetworking\"\n  name        = \"prod\"\n  environment = \"prod\"\n  vpc_cidr    = \"10.0.0.0\u002F16\"\n  azs         = [\"us-east-1a\", \"us-east-1b\", \"us-east-1c\"]\n  tags        = local.common_tags\n}\n\nmodule \"compute\" {\n  source             = \"..\u002F..\u002Fmodules\u002Fcompute\"\n  name               = \"prod\"\n  environment        = \"prod\"\n  vpc_id             = module.networking.vpc_id\n  private_subnet_ids = module.networking.private_subnet_ids\n  instance_type      = \"t3.large\"\n  min_size           = 3\n  max_size           = 10\n  tags               = local.common_tags\n}\n```\n\n### 8 Module Design Rules\n\n1. **Expose what's needed, hide what's not** — minimal variable surface\n2. **Use `for_each` over `count`** — stable resource addressing\n3. **Validate inputs** — `validation` blocks catch errors at plan time\n4. **Default to secure** — encryption on, public access off, least privilege\n5. **Version everything** — semver for modules, `~>` for providers\n6. **No provider config in modules** — providers configured in root only\n7. **Use `moved` blocks for refactoring** — not `state mv`\n8. **Test with examples** — `examples\u002F` directory with working configurations\n\n---\n\n## Phase 5: Multi-Environment Strategy\n\n### Environment Comparison\n\n| Aspect | Dev | Staging | Prod |\n|--------|-----|---------|------|\n| Instance sizes | Small\u002Fmicro | Match prod types | Right-sized |\n| Replica count | 1 | 2 | 3+ (HA) |\n| Multi-AZ | Optional | Yes | Yes |\n| Backup retention | 1 day | 7 days | 30+ days |\n| Monitoring | Basic | Full | Full + PagerDuty |\n| Auto-scaling | Off | On | On |\n| WAF\u002FShield | Off | On | On + Advanced |\n| State access | Dev team | DevOps | DevOps only |\n\n### Variable Hierarchy Pattern\n\n```hcl\n# modules\u002Fcompute\u002Fvariables.tf\nvariable \"instance_type\" {\n  type    = string\n  default = \"t3.micro\"  # Safe default\n}\n\nvariable \"min_size\" {\n  type    = number\n  default = 1\n}\n\nvariable \"enable_deletion_protection\" {\n  type    = bool\n  default = true  # Safe default — must explicitly disable for dev\n}\n```\n\n```hcl\n# environments\u002Fdev\u002Fterraform.tfvars\ninstance_type              = \"t3.micro\"\nmin_size                   = 1\nenable_deletion_protection = false\n\n# environments\u002Fprod\u002Fterraform.tfvars\ninstance_type              = \"t3.large\"\nmin_size                   = 3\nenable_deletion_protection = true\n```\n\n### Promotion Strategy\n\n```\ndev → staging → prod\n │       │        │\n │       │        └─ Manual approval required\n │       └─ Auto-apply after plan review\n └─ Auto-apply on merge to dev branch\n```\n\n---\n\n## Phase 6: Security Hardening\n\n### 15-Point Security Checklist\n\n**P0 — Mandatory:**\n- [ ] No secrets in `.tf` files, `.tfvars`, or state (use vault\u002FSSM\u002Fsecrets manager)\n- [ ] State backend encrypted at rest with customer-managed keys\n- [ ] State access restricted to CI\u002FCD service accounts only\n- [ ] `prevent_destroy` on critical resources (databases, S3 with data)\n- [ ] Provider credentials via environment variables or OIDC, never in config\n- [ ] `.gitignore` includes `*.tfvars` with secrets, `.terraform\u002F`, `*.tfstate*`\n\n**P1 — Required:**\n- [ ] OIDC for CI\u002FCD auth (no long-lived access keys)\n- [ ] Least-privilege IAM for Terraform service account\n- [ ] Security group rules explicit (no `0.0.0.0\u002F0` ingress except ALB on 443)\n- [ ] Encryption enabled on all data stores (RDS, S3, EBS, ElastiCache)\n- [ ] VPC flow logs enabled\n- [ ] CloudTrail\u002Faudit logging for all API calls\n\n**P2 — Recommended:**\n- [ ] OPA\u002FSentinel policies enforced in CI\n- [ ] `tfsec` or `checkov` in CI pipeline\n- [ ] Separate AWS accounts per environment (AWS Organizations)\n\n### Secrets Management Decision Tree\n\n```\nNeed a secret in Terraform?\n├── Runtime secret (app needs at runtime)\n│   └── Use AWS Secrets Manager \u002F HashiCorp Vault\n│       └── Reference via data source, pass ARN to app\n├── Terraform-time secret (provider needs it)\n│   └── Environment variable (TF_VAR_xxx) or OIDC\n└── Generated secret (Terraform creates it)\n    └── random_password resource → store in Secrets Manager\n        └── Mark output as sensitive = true\n```\n\n### OIDC Authentication (GitHub Actions → AWS)\n\n```hcl\n# No access keys needed\ndata \"aws_iam_openid_connect_provider\" \"github\" {\n  url = \"https:\u002F\u002Ftoken.actions.githubusercontent.com\"\n}\n\nresource \"aws_iam_role\" \"terraform_ci\" {\n  name = \"terraform-ci\"\n  assume_role_policy = jsonencode({\n    Version = \"2012-10-17\"\n    Statement = [{\n      Effect = \"Allow\"\n      Principal = { Federated = data.aws_iam_openid_connect_provider.github.arn }\n      Action = \"sts:AssumeRoleWithWebIdentity\"\n      Condition = {\n        StringEquals = {\n          \"token.actions.githubusercontent.com:aud\" = \"sts.amazonaws.com\"\n        }\n        StringLike = {\n          \"token.actions.githubusercontent.com:sub\" = \"repo:org\u002Finfra:*\"\n        }\n      }\n    }]\n  })\n}\n```\n\n---\n\n## Phase 7: Testing Strategy\n\n### 4-Level Test Pyramid\n\n| Level | Tool | What It Tests | When |\n|-------|------|---------------|------|\n| **Static** | `terraform validate`, `tflint`, `tfsec`, `checkov` | Syntax, best practices, security | Every commit |\n| **Plan** | `terraform plan` + policy checks | Expected changes, no surprises | Every PR |\n| **Contract** | `terratest` \u002F `tftest` (TF 1.6+) | Module inputs\u002Foutputs, behavior | PR + nightly |\n| **Integration** | `terratest` with real cloud | Actual infrastructure works | Nightly\u002Fweekly |\n\n### Native Terraform Test (TF 1.6+)\n\n```hcl\n# tests\u002Fnetworking.tftest.hcl\nrun \"creates_vpc_with_correct_cidr\" {\n  command = plan\n\n  variables {\n    name        = \"test\"\n    environment = \"dev\"\n    vpc_cidr    = \"10.0.0.0\u002F16\"\n    azs         = [\"us-east-1a\"]\n  }\n\n  assert {\n    condition     = aws_vpc.main.cidr_block == \"10.0.0.0\u002F16\"\n    error_message = \"VPC CIDR doesn't match input\"\n  }\n\n  assert {\n    condition     = aws_vpc.main.enable_dns_hostnames == true\n    error_message = \"DNS hostnames should be enabled\"\n  }\n}\n\nrun \"rejects_invalid_environment\" {\n  command = plan\n  expect_failures = [var.environment]\n\n  variables {\n    name        = \"test\"\n    environment = \"invalid\"\n    vpc_cidr    = \"10.0.0.0\u002F16\"\n    azs         = [\"us-east-1a\"]\n  }\n}\n```\n\n### Static Analysis CI Step\n\n```yaml\n- name: Terraform Lint & Security\n  run: |\n    terraform fmt -check -recursive\n    terraform validate\n    tflint --recursive\n    tfsec .\n    checkov -d . --framework terraform\n```\n\n### 7 Testing Rules\n\n1. **Static analysis on every commit** — catches 80% of issues for free\n2. **Plan review on every PR** — humans approve infrastructure changes\n3. **Native tests for modules** — `terraform test` is built-in, use it\n4. **Integration tests destroy after** — `defer cleanup` to avoid orphaned resources\n5. **Test in isolated account** — never test against production state\n6. **Pin test dependencies** — terratest Go modules, provider versions\n7. **Cost estimation in CI** — `infracost` to catch expensive surprises\n\n---\n\n## Phase 8: CI\u002FCD Pipeline\n\n### GitHub Actions Pipeline\n\n```yaml\nname: Terraform\non:\n  pull_request:\n    paths: ['infrastructure\u002F**']\n  push:\n    branches: [main]\n    paths: ['infrastructure\u002F**']\n\npermissions:\n  id-token: write    # OIDC\n  contents: read\n  pull-requests: write  # PR comments\n\njobs:\n  validate:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: hashicorp\u002Fsetup-terraform@v3\n        with:\n          terraform_version: \"1.7.x\"\n      - run: terraform fmt -check -recursive\n      - run: terraform init -backend=false\n      - run: terraform validate\n      - run: tflint --recursive\n      - run: tfsec . --soft-fail\n\n  plan:\n    needs: validate\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        environment: [dev, staging, prod]\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: aws-actions\u002Fconfigure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role\u002Fterraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp\u002Fsetup-terraform@v3\n      - working-directory: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\n        run: |\n          terraform init\n          terraform plan -out=tfplan -no-color\n      - uses: actions\u002Fupload-artifact@v4\n        with:\n          name: tfplan-${{ matrix.environment }}\n          path: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\u002Ftfplan\n\n  apply:\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    needs: plan\n    runs-on: ubuntu-latest\n    environment: production  # Requires approval\n    strategy:\n      matrix:\n        environment: [dev, staging, prod]\n      max-parallel: 1  # Sequential: dev → staging → prod\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: aws-actions\u002Fconfigure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role\u002Fterraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp\u002Fsetup-terraform@v3\n      - uses: actions\u002Fdownload-artifact@v4\n        with:\n          name: tfplan-${{ matrix.environment }}\n          path: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\n      - working-directory: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\n        run: terraform apply tfplan\n```\n\n### CI\u002FCD Rules\n\n1. **Never `apply` from local machines** — CI\u002FCD only\n2. **Plan artifact = apply input** — same plan that was reviewed gets applied\n3. **Sequential environment promotion** — dev → staging → prod, not parallel\n4. **Production requires approval** — GitHub Environment protection rules\n5. **Drift detection on schedule** — weekly `plan` to detect manual changes\n6. **Cost estimation on PR** — Infracost or similar\n\n---\n\n## Phase 9: Resource Patterns\n\n### Tagging Strategy\n\n```hcl\nlocals {\n  common_tags = {\n    Project     = var.project_name\n    Environment = var.environment\n    ManagedBy   = \"terraform\"\n    Team        = var.team\n    CostCenter  = var.cost_center\n    Repository  = \"github.com\u002Forg\u002Finfrastructure\"\n  }\n}\n\n# Apply to all resources\nresource \"aws_instance\" \"app\" {\n  # ...\n  tags = merge(local.common_tags, {\n    Name = \"${var.name}-app\"\n    Role = \"application\"\n  })\n}\n```\n\n### Naming Convention\n\n```\n{project}-{environment}-{component}-{qualifier}\n```\n\nExamples: `acme-prod-vpc-main`, `acme-staging-rds-primary`, `acme-prod-alb-api`\n\n### Common Patterns\n\n**Conditional Resource Creation:**\n```hcl\nresource \"aws_cloudwatch_metric_alarm\" \"cpu\" {\n  count = var.environment == \"prod\" ? 1 : 0\n  # Only create alarms in prod\n}\n```\n\n**Dynamic Blocks:**\n```hcl\nresource \"aws_security_group\" \"app\" {\n  name   = \"${var.name}-app\"\n  vpc_id = var.vpc_id\n\n  dynamic \"ingress\" {\n    for_each = var.ingress_rules\n    content {\n      from_port   = ingress.value.port\n      to_port     = ingress.value.port\n      protocol    = \"tcp\"\n      cidr_blocks = ingress.value.cidrs\n      description = ingress.value.description\n    }\n  }\n}\n```\n\n**Data Source for Cross-Stack References:**\n```hcl\n# Instead of hardcoding VPC ID\ndata \"terraform_remote_state\" \"networking\" {\n  backend = \"s3\"\n  config = {\n    bucket = \"company-terraform-state\"\n    key    = \"environments\u002Fprod\u002Fnetworking\u002Fterraform.tfstate\"\n    region = \"us-east-1\"\n  }\n}\n\n# Use: data.terraform_remote_state.networking.outputs.vpc_id\n```\n\n---\n\n## Phase 10: Drift Management\n\n### Drift Detection Schedule\n\n```yaml\n# .github\u002Fworkflows\u002Fdrift-detection.yml\nname: Drift Detection\non:\n  schedule:\n    - cron: '0 8 * * 1'  # Weekly Monday 8 AM UTC\n\njobs:\n  detect:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        environment: [dev, staging, prod]\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: aws-actions\u002Fconfigure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role\u002Fterraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp\u002Fsetup-terraform@v3\n      - working-directory: infrastructure\u002Fenvironments\u002F${{ matrix.environment }}\n        run: |\n          terraform init\n          terraform plan -detailed-exitcode -no-color 2>&1 | tee plan.txt\n          EXIT_CODE=$?\n          if [ $EXIT_CODE -eq 2 ]; then\n            echo \"::warning::Drift detected in ${{ matrix.environment }}\"\n            # Send Slack alert\n          fi\n```\n\n### Drift Response Playbook\n\n| Drift Type | Response |\n|-----------|----------|\n| Manual console change (cosmetic) | Import or update config to match |\n| Manual console change (critical) | Investigate who\u002Fwhy, then align |\n| Auto-scaling \u002F ASG changes | Expected — use `ignore_changes` for dynamic attributes |\n| AWS service updates | Update provider version, review changelog |\n| Security group modified manually | 🚨 Security incident — investigate immediately |\n\n### `ignore_changes` Decision Guide\n\nUse `ignore_changes` ONLY for:\n- Attributes modified by the application at runtime (e.g., ASG desired count)\n- Tags managed by external systems (e.g., AWS Backup tags)\n- Attributes that drift due to API behavior (e.g., default security group rules)\n\n**Never `ignore_changes` for:**\n- Security configurations\n- Network rules\n- IAM policies\n- Encryption settings\n\n---\n\n## Phase 11: Cost Optimization\n\n### Infracost in CI\n\n```yaml\n- name: Infracost\n  run: |\n    infracost breakdown --path infrastructure\u002Fenvironments\u002Fprod\u002F \\\n      --format json --out-file infracost.json\n    infracost output --path infracost.json --format github-comment \\\n      --out-file comment.md\n    # Post as PR comment\n```\n\n### Cost Optimization Checklist\n\n| Strategy | Savings | Implementation |\n|----------|---------|----------------|\n| Reserved Instances \u002F Savings Plans | 30-60% | Annual commitment for stable workloads |\n| Right-sizing | 20-40% | Monitor CPU\u002Fmemory, downsize over-provisioned |\n| Spot\u002FPreemptible for non-critical | 60-90% | Batch jobs, dev environments |\n| S3 lifecycle policies | 20-50% storage | Transition to IA → Glacier → delete |\n| NAT Gateway alternatives | $30-100\u002Fmo per GW | NAT instances for dev, VPC endpoints |\n| Dev environment scheduling | 60-70% | Destroy nights\u002Fweekends, recreate on demand |\n| Unused resource cleanup | Variable | Tag with TTL, auto-delete untagged after 7 days |\n\n### Tagging for Cost Allocation\n\nRequired cost tags (enforce via policy):\n- `CostCenter` — maps to business unit\n- `Environment` — dev\u002Fstaging\u002Fprod\n- `Project` — which project owns this\n- `Team` — responsible team\n- `ManagedBy` — terraform\u002Fmanual\u002Fother\n\n---\n\n## Phase 12: Advanced Patterns\n\n### Terragrunt for DRY Environments\n\nWhen you have 5+ environments with identical module structures, Terragrunt eliminates repetition:\n\n```hcl\n# terragrunt.hcl (root)\nremote_state {\n  backend = \"s3\"\n  generate = { path = \"backend.tf\", if_exists = \"overwrite_terragrunt\" }\n  config = {\n    bucket         = \"company-terraform-state\"\n    key            = \"${path_relative_to_include()}\u002Fterraform.tfstate\"\n    region         = \"us-east-1\"\n    encrypt        = true\n    dynamodb_table = \"terraform-state-lock\"\n  }\n}\n```\n\n### Import Block (TF 1.5+)\n\n```hcl\n# Declarative import — reviewable in PR\nimport {\n  to = aws_s3_bucket.existing\n  id = \"my-existing-bucket\"\n}\n\nresource \"aws_s3_bucket\" \"existing\" {\n  bucket = \"my-existing-bucket\"\n  # Write config to match existing resource\n}\n```\n\n### Provider Aliases for Multi-Region\n\n```hcl\nprovider \"aws\" {\n  region = \"us-east-1\"\n}\n\nprovider \"aws\" {\n  alias  = \"eu\"\n  region = \"eu-west-1\"\n}\n\nmodule \"eu_networking\" {\n  source = \"..\u002F..\u002Fmodules\u002Fnetworking\"\n  providers = { aws = aws.eu }\n  # ...\n}\n```\n\n### `moved` Block for Refactoring\n\n```hcl\n# Rename without destroy+create\nmoved {\n  from = aws_instance.app\n  to   = aws_instance.application\n}\n\n# Move into module\nmoved {\n  from = aws_instance.app\n  to   = module.compute.aws_instance.app\n}\n```\n\n---\n\n## Phase 13: Disaster Recovery & Migration\n\n### State Recovery\n\n```bash\n# Enable versioning on state bucket (BEFORE you need it)\naws s3api put-bucket-versioning \\\n  --bucket company-terraform-state \\\n  --versioning-configuration Status=Enabled\n\n# List state versions\naws s3api list-object-versions \\\n  --bucket company-terraform-state \\\n  --prefix environments\u002Fprod\u002Fnetworking\u002Fterraform.tfstate\n\n# Restore previous version\naws s3api get-object \\\n  --bucket company-terraform-state \\\n  --key environments\u002Fprod\u002Fnetworking\u002Fterraform.tfstate \\\n  --version-id \"versionId123\" \\\n  restored-state.tfstate\n```\n\n### Migration Checklist (Moving Between Backends)\n\n1. [ ] `terraform state pull > backup.tfstate` — backup current state\n2. [ ] Update `backend.tf` with new backend config\n3. [ ] `terraform init -migrate-state` — Terraform copies state\n4. [ ] `terraform plan` — verify no changes (state matches)\n5. [ ] Test apply on non-critical resource\n6. [ ] Delete old state after verification period (7 days)\n\n### Breaking Changes Protocol\n\nWhen upgrading major Terraform or provider versions:\n1. Read changelog for breaking changes\n2. Test upgrade in dev first\n3. Update `.terraform.lock.hcl`\n4. Run `terraform plan` in all environments\n5. Apply dev → staging → prod with 24h gaps\n\n---\n\n## Phase 14: Quality Scoring\n\n### 100-Point Terraform Quality Rubric\n\n| Dimension | Weight | Score Range |\n|-----------|--------|-------------|\n| State management | 20% | 0-20 |\n| Security posture | 20% | 0-20 |\n| Module design | 15% | 0-15 |\n| Testing coverage | 15% | 0-15 |\n| CI\u002FCD automation | 10% | 0-10 |\n| Documentation | 10% | 0-10 |\n| Cost governance | 5% | 0-5 |\n| Drift management | 5% | 0-5 |\n\n**Scoring Guide:**\n- **90-100**: Production-grade, fully automated, battle-tested\n- **70-89**: Solid foundation, some gaps to address\n- **50-69**: Functional but risky — prioritize security and state management\n- **Below 50**: Stop deploying and fix fundamentals\n\n### 10 Terraform Commandments\n\n1. **Remote state with locking or don't start**\n2. **Never hardcode secrets — not in code, not in state if avoidable**\n3. **Plan is sacred — review every plan, apply only reviewed plans**\n4. **Modules are contracts — version them, test them, document them**\n5. **Environments are isolated — separate state, separate accounts ideally**\n6. **`for_each` over `count` — stable addressing saves you**\n7. **CI\u002FCD applies, humans don't — no local `terraform apply` in prod**\n8. **Tag everything — cost allocation, ownership, lifecycle**\n9. **Drift is a bug — detect it weekly, fix it immediately**\n10. **Upgrade deliberately — test in dev, read changelogs, lock versions**\n\n### 10 Common Mistakes\n\n| Mistake | Impact | Fix |\n|---------|--------|-----|\n| Local state for team projects | State conflicts, data loss | Remote backend day 1 |\n| Secrets in `.tfvars` committed to git | Credential exposure | Use vault\u002FSSM + env vars |\n| `count` for optional resources | Index shift on removal | `for_each` with conditional map |\n| Monolithic state file | Slow plans, blast radius | Split by component (networking\u002Fcompute\u002Fdata) |\n| No `prevent_destroy` on data stores | Accidental database deletion | Lifecycle rule on stateful resources |\n| Unpinned module versions | Breaking changes on init | Pin with `?ref=v1.2.3` or `version = \"~> 1.2\"` |\n| `terraform apply -auto-approve` in prod | Unreviewed changes | Plan artifact → human review → apply |\n| Using workspaces as environments | Shared state, shared blast radius | Separate directories + backends per env |\n| No cost estimation in CI | $10K surprise bills | Infracost or similar on every PR |\n| Manual changes \"just this once\" | Permanent drift | Always go through code, even for emergencies |\n\n---\n\n## Natural Language Commands\n\n- \"Review this Terraform code\" → Run Phase 1 health check + static analysis recommendations\n- \"Design infrastructure for [service]\" → Phase 2 structure + Phase 4 module design\n- \"Set up remote state\" → Phase 3 backend configuration\n- \"Create a module for [resource]\" → Phase 4 module template with variables\u002Foutputs\n- \"Compare environments\" → Phase 5 environment matrix\n- \"Security audit my Terraform\" → Phase 6 security checklist\n- \"Add tests to this module\" → Phase 7 native test examples\n- \"Set up CI\u002FCD for Terraform\" → Phase 8 GitHub Actions pipeline\n- \"Check for drift\" → Phase 10 drift detection setup\n- \"Estimate infrastructure costs\" → Phase 11 Infracost integration\n- \"Migrate state to new backend\" → Phase 13 migration checklist\n- \"Score this Terraform project\" → Phase 14 quality rubric\n\n---\n\n## ⚡ Level Up\n\nThis skill covers Terraform methodology and best practices. For industry-specific infrastructure patterns:\n\n- **SaaS Infrastructure** → [AfrexAI SaaS Context Pack ($47)](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n- **Fintech Compliance Infrastructure** → [AfrexAI Fintech Context Pack ($47)](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n- **Healthcare HIPAA Infrastructure** → [AfrexAI Healthcare Context Pack ($47)](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n\n## 🔗 More Free Skills by AfrexAI\n\n- `clawhub install afrexai-devops-engine` — Complete DevOps & Platform Engineering\n- `clawhub install afrexai-cybersecurity-engine` — Security Hardening & Compliance\n- `clawhub install afrexai-system-architect` — System Architecture Decision Frameworks\n- `clawhub install afrexai-api-architect` — API Design & Lifecycle Management\n- `clawhub install afrexai-cicd-engineering` — CI\u002FCD Pipeline Engineering\n\nBrowse all AfrexAI skills: [clawhub.com](https:\u002F\u002Fclawhub.com) → Search \"afrexai\"\n\nStorefront: [afrexai-cto.github.io\u002Fcontext-packs](https:\u002F\u002Fafrexai-cto.github.io\u002Fcontext-packs\u002F)\n",{"name":5,"description":7},"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fa\u002Fafrexai-terraform-production",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Terraform & Infrastructure as Code Production Engineering\"",{"tool":39,"command":40},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Terraform & Infrastructure as Code Production Engineering\"",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Terraform & Infrastructure as Code Production Engineering\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fa\u002Fafrexai-terraform-production\u002FSKILL.md",true,[],[48,56,63,70,77,84],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":55},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":55},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":55},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":55},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":55},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":55},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]