{"id":"549e2dc5-756c-4f76-9430-bccda9d43e1a","entityType":"agent","slug":"clawhub-skills-1kalin-afrexai-terraform-production","name":"Terraform & Infrastructure as Code Production Engineering","canonicalUrl":"https://www.xpersona.co/agent/clawhub-skills-1kalin-afrexai-terraform-production","canonicalPath":"/agent/clawhub-skills-1kalin-afrexai-terraform-production","generatedAt":"2026-10-10T05:47:56.496Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"description":"Complete Terraform & IaC production methodology — project structure, module design, state management, multi-environment deployment, security hardening, testing, CI/CD pipelines, cost optimization, and drift management. Use when designing infrastructure, writing Terraform, reviewing IaC, or managing cloud environments. --- name: Terraform & Infrastructure as Code Production Engineering description: Complete Terraform & IaC production methodology — project structure, module design, state management, multi-environment deployment, security hardening, testing, CI/CD pipelines, cost optimization, and drift management. Use when designing infrastructure, writing Terraform, reviewing IaC, or managing cloud environments. --- Terraform & Inf","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. Last updated 4/15/2026.","installCommand":"clawhub skill install skills:1kalin:afrexai-terraform-production","sourceUrl":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-terraform-production","homepage":null,"primaryLinks":[{"label":"View on ClawHub","url":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-terraform-production","kind":"source"}],"safetyScore":84,"overallRank":62,"popularityScore":50,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Complete Terraform & IaC production methodology — project structure, module design, state management, multi-environment deployment, security hardening, testing,"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"no-adoption-signals","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No source adoption metrics were available."},"stars":null,"forks":null,"downloads":null,"packageName":null,"latestVersion":null,"tractionLabel":null},"release":{"evidence":{"source":"agent-index","verified":false,"confidence":"medium","updatedAt":"2026-02-25T05:52:56.333Z","emptyReason":null},"lastUpdatedAt":"2026-04-15T00:45:39.800Z","lastCrawledAt":"2026-02-25T05:52:56.333Z","lastIndexedAt":null,"nextCrawlAt":"2026-02-26T05:52:56.333Z","lastVerifiedAt":null,"highlights":[]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install skills:1kalin:afrexai-terraform-production","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T05:47:56.496Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-terraform-production/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"readme":"---\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/CD 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/GCS/Azure 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/staging/prod) | 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/SSM/secrets manager | Hardcoded secrets anywhere |\n| 8 | Drift detection | Scheduled drift checks (weekly minimum) | No drift monitoring |\n\n**Score: /16** (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/\n├── modules/                    # Reusable modules (internal registry)\n│   ├── networking/\n│   │   ├── main.tf\n│   │   ├── variables.tf\n│   │   ├── outputs.tf\n│   │   ├── versions.tf\n│   │   └── README.md\n│   ├── compute/\n│   ├── database/\n│   └── monitoring/\n├── environments/               # Environment-specific configs\n│   ├── dev/\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/\n│   └── prod/\n├── global/                     # Shared resources (IAM, DNS, etc.)\n│   ├── iam/\n│   ├── dns/\n│   └── networking/\n├── scripts/                    # Helper scripts (import, migration)\n├── policies/                   # OPA/Sentinel policies\n└── .github/workflows/          # CI/CD 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/team 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/prod/networking/terraform.tfstate\"\n    region         = \"us-east-1\"\n    encrypt        = true\n    dynamodb_table = \"terraform-state-lock\"\n    kms_key_id     = \"alias/terraform-state\"\n  }\n}\n```\n\n### State Key Strategy\n\n```\n{org}/{environment}/{component}/terraform.tfstate\n```\n\nExamples:\n- `acme/prod/networking/terraform.tfstate`\n- `acme/prod/compute/terraform.tfstate`\n- `acme/global/iam/terraform.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/CD 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/prod/main.tf\nmodule \"networking\" {\n  source      = \"../../modules/networking\"\n  name        = \"prod\"\n  environment = \"prod\"\n  vpc_cidr    = \"10.0.0.0/16\"\n  azs         = [\"us-east-1a\", \"us-east-1b\", \"us-east-1c\"]\n  tags        = local.common_tags\n}\n\nmodule \"compute\" {\n  source             = \"../../modules/compute\"\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/` 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/micro | 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/Shield | Off | On | On + Advanced |\n| State access | Dev team | DevOps | DevOps only |\n\n### Variable Hierarchy Pattern\n\n```hcl\n# modules/compute/variables.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/dev/terraform.tfvars\ninstance_type              = \"t3.micro\"\nmin_size                   = 1\nenable_deletion_protection = false\n\n# environments/prod/terraform.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/SSM/secrets manager)\n- [ ] State backend encrypted at rest with customer-managed keys\n- [ ] State access restricted to CI/CD 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/`, `*.tfstate*`\n\n**P1 — Required:**\n- [ ] OIDC for CI/CD auth (no long-lived access keys)\n- [ ] Least-privilege IAM for Terraform service account\n- [ ] Security group rules explicit (no `0.0.0.0/0` ingress except ALB on 443)\n- [ ] Encryption enabled on all data stores (RDS, S3, EBS, ElastiCache)\n- [ ] VPC flow logs enabled\n- [ ] CloudTrail/audit logging for all API calls\n\n**P2 — Recommended:**\n- [ ] OPA/Sentinel 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 / 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://token.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/infra:*\"\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` / `tftest` (TF 1.6+) | Module inputs/outputs, behavior | PR + nightly |\n| **Integration** | `terratest` with real cloud | Actual infrastructure works | Nightly/weekly |\n\n### Native Terraform Test (TF 1.6+)\n\n```hcl\n# tests/networking.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/16\"\n    azs         = [\"us-east-1a\"]\n  }\n\n  assert {\n    condition     = aws_vpc.main.cidr_block == \"10.0.0.0/16\"\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/16\"\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/CD Pipeline\n\n### GitHub Actions Pipeline\n\n```yaml\nname: Terraform\non:\n  pull_request:\n    paths: ['infrastructure/**']\n  push:\n    branches: [main]\n    paths: ['infrastructure/**']\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/checkout@v4\n      - uses: hashicorp/setup-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/checkout@v4\n      - uses: aws-actions/configure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role/terraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp/setup-terraform@v3\n      - working-directory: infrastructure/environments/${{ matrix.environment }}\n        run: |\n          terraform init\n          terraform plan -out=tfplan -no-color\n      - uses: actions/upload-artifact@v4\n        with:\n          name: tfplan-${{ matrix.environment }}\n          path: infrastructure/environments/${{ matrix.environment }}/tfplan\n\n  apply:\n    if: github.ref == 'refs/heads/main'\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/checkout@v4\n      - uses: aws-actions/configure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role/terraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp/setup-terraform@v3\n      - uses: actions/download-artifact@v4\n        with:\n          name: tfplan-${{ matrix.environment }}\n          path: infrastructure/environments/${{ matrix.environment }}\n      - working-directory: infrastructure/environments/${{ matrix.environment }}\n        run: terraform apply tfplan\n```\n\n### CI/CD Rules\n\n1. **Never `apply` from local machines** — CI/CD 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/org/infrastructure\"\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/prod/networking/terraform.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/workflows/drift-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/checkout@v4\n      - uses: aws-actions/configure-aws-credentials@v4\n        with:\n          role-to-assume: arn:aws:iam::role/terraform-ci\n          aws-region: us-east-1\n      - uses: hashicorp/setup-terraform@v3\n      - working-directory: infrastructure/environments/${{ 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/why, then align |\n| Auto-scaling / 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/environments/prod/ \\\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 / Savings Plans | 30-60% | Annual commitment for stable workloads |\n| Right-sizing | 20-40% | Monitor CPU/memory, downsize over-provisioned |\n| Spot/Preemptible 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/mo per GW | NAT instances for dev, VPC endpoints |\n| Dev environment scheduling | 60-70% | Destroy nights/weekends, 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/staging/prod\n- `Project` — which project owns this\n- `Team` — responsible team\n- `ManagedBy` — terraform/manual/other\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()}/terraform.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 = \"../../modules/networking\"\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/prod/networking/terraform.tfstate\n\n# Restore previous version\naws s3api get-object \\\n  --bucket company-terraform-state \\\n  --key environments/prod/networking/terraform.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/CD 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/CD 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/SSM + 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/compute/data) |\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/outputs\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/CD 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://afrexai-cto.github.io/context-packs/)\n- **Fintech Compliance Infrastructure** → [AfrexAI Fintech Context Pack ($47)](https://afrexai-cto.github.io/context-packs/)\n- **Healthcare HIPAA Infrastructure** → [AfrexAI Healthcare Context Pack ($47)](https://afrexai-cto.github.io/context-packs/)\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/CD Pipeline Engineering\n\nBrowse all AfrexAI skills: [clawhub.com](https://clawhub.com) → Search \"afrexai\"\n\nStorefront: [afrexai-cto.github.io/context-packs](https://afrexai-cto.github.io/context-packs/)\n","readmeExcerpt":"--- name: Terraform & Infrastructure as Code Production Engineering description: Complete Terraform & IaC production methodology — project structure, module design, state management, multi-environment deployment, security hardening, testing, CI/CD pipelines, cost optimization, and drift management. Use when designing infrastructure, writing Terraform, reviewing IaC, or managing cloud environments. --- Terraform & Inf","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"infrastructure/\n├── modules/                    # Reusable modules (internal registry)\n│   ├── networking/\n│   │   ├── main.tf\n│   │   ├── variables.tf\n│   │   ├── outputs.tf\n│   │   ├── versions.tf\n│   │   └── README.md\n│   ├── compute/\n│   ├── database/\n│   └── monitoring/\n├── environments/               # Environment-specific configs\n│   ├── dev/\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/\n│   └── prod/\n├── global/                     # Shared resources (IAM, DNS, etc.)\n│   ├── iam/\n│   ├── dns/\n│   └── networking/\n├── scripts/                    # Helper scripts (import, migration)\n├── policies/                   # OPA/Sentinel policies\n└── .github/workflows/          # CI/CD pipelines"},{"language":"hcl","snippet":"# backend.tf\nterraform {\n  backend \"s3\" {\n    bucket         = \"company-terraform-state\"\n    key            = \"environments/prod/networking/terraform.tfstate\"\n    region         = \"us-east-1\"\n    encrypt        = true\n    dynamodb_table = \"terraform-state-lock\"\n    kms_key_id     = \"alias/terraform-state\"\n  }\n}"},{"language":"text","snippet":"{org}/{environment}/{component}/terraform.tfstate"},{"language":"hcl","snippet":"# 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}"},{"language":"hcl","snippet":"# 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}"},{"language":"hcl","snippet":"# environments/prod/main.tf\nmodule \"networking\" {\n  source      = \"../../modules/networking\"\n  name        = \"prod\"\n  environment = \"prod\"\n  vpc_cidr    = \"10.0.0.0/16\"\n  azs         = [\"us-east-1a\", \"us-east-1b\", \"us-east-1c\"]\n  tags        = local.common_tags\n}\n\nmodule \"compute\" {\n  source             = \"../../modules/compute\"\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}"}],"parameters":{},"dependencies":[],"permissions":[],"extractedFiles":[],"languages":["typescript"],"docsSourceLabel":"CLAWHUB","editorialOverview":"Complete Terraform & IaC production methodology — project structure, module design, state management, multi-environment deployment, security hardening, testing, CI/CD pipelines, cost optimization, and drift management. Use when designing infrastructure, writing Terraform, reviewing IaC, or managing cloud environments. --- name: Terraform & Infrastructure as Code Production Engineering description: Complete Terraform & IaC production methodology — project structure, module design, state management, multi-environment deployment, security hardening, testing, CI/CD pipelines, cost optimization, and drift management. Use when designing infrastructure, writing Terraform, reviewing IaC, or managing cloud environments. --- Terraform & Inf","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":432,"uniquenessScore":58,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T05:47:56.496Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}