Generated banner for Tf Best Practices
Generated logo for Tf Best Practices

Tf Best Practices

AWSOfficialPublished by AWS

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Best-practice authoring guidance AND a read-only policy gate for AWS Terraform generated by a migration skill. Load during any phase that writes a terraform/ directory — first as the "what to emit" posture rules + security-baseline spec, then after writing as the deterministic policy verdict. Read-only: it reports whether the generated Terraform passes; it never edits .tf files, never touches .phase-status.json, and never decides phase completion. Complements (does not replace) terraform fmt/init/validate.
— the description by AWS

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

tf-best-practices provides a structured approach to authoring and validating AWS Terraform code. It functions as a two-part system: an authoring guide that defines security posture rules before code generation, and a read-only policy gate that evaluates generated Terraform against those rules after it is written. The skill is designed to be integrated into migration workflows, providing deterministic verdicts and actionable fix hints without modifying the underlying files.

What it does

  • Provides security posture rules for authoring AWS Terraform.
  • Executes a read-only policy check on generated Terraform directories.
  • Generates machine-readable JSON reports detailing policy violations.
  • Offers specific fix hints for identified infrastructure issues.
  • Validates migration artifacts including database and deployment configurations.
  • Supports a multi-stage validation protocol including fmt, init, and validate.

When to use it

  • Before writing Terraform code to ensure adherence to security posture rules.
  • After generating Terraform to verify compliance with defined policy gates.
  • When integrating automated validation into a migration workflow.
  • To identify and remediate infrastructure configuration issues during development.

Advantages

  • Enforces consistent security standards across generated infrastructure.
  • Provides actionable feedback with file and line-specific remediation hints.
  • Operates as a read-only tool that does not modify user files.
  • Functions without requiring provider downloads or active registry connections.
  • Integrates into existing migration pipelines as a deterministic gate.

Usage examples

“Check the generated terraform/ directory for policy violations.”
The skill runs the policy checker against the specified directory and returns a JSON report containing any identified violations and corresponding fix hints.
“What are the security requirements for an internet-facing ALB?”
The skill provides the posture rules requiring an HTTPS listener on port 443 and an HTTP redirect to HTTPS on port 80.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/aws/tf-best-practices/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip tf-best-practices.zip -d .agents/skills

Documentation by AWS

tf-best-practices — Generated-IaC posture rules + read-only policy gate

A shared authoring guide and verdict producer, not a workflow. It answers two questions for a phase that generates AWS Terraform:

  1. Before writing — "what security posture must the generated terraform/ follow?" (the posture rules + the baseline.tf account-hardening spec)

  2. After writing — "does the generated terraform/ pass policy?" (a deterministic, read-only verdict + a machine-readable report)

Routing — load the part that matches your context

This skill is entered at two touchpoints in the caller's Generate flow, with the caller's own terraform-authoring work in between. The caller states which touchpoint it is at when it loads this skill, and reads the corresponding part:

Caller contextLoadWhy
About to author terraform/ (before writing)Part 1 → references/security-posture-rules.mdThe "what to emit" AWS authoring rules (gate-enforced + authoring-only + compliance-conditional).
terraform/ written, ready to validate (after writing)Part 2 → references/terraform-validation.md + run the gate scriptThe fmt → init → validate → policy protocol and the read-only verdict.

Everything this skill states is source-cloud-agnostic (pure AWS Terraform). Any GCP/Heroku detection or artifact reading is the caller's job; where a rule needs a caller-known fact (e.g. declared compliance frameworks), the caller passes it as a caller-context signal — see references/security-posture-rules.md § Caller-context signals.

Boundary (read this first)

This unit is a verdict producer, never a mutator. Its entire write surface is the JSON verdict it is asked to emit. Specifically it MUST NOT:

  • edit, format, or rewrite any .tf file (the caller owns remediation),

  • read or write .phase-status.json or any run-state file (interpreter-owned),

  • decide whether a phase may complete, or prompt the user (caller policy).

The caller (a migration skill's Generate phase) owns: the fix-and-retry loop that edits the .tf it generated, terraform fmt auto-apply, the retry/skip/abort prompt, the Phase Completion gate, and every .phase-status.json write. See the consuming skill's generate phase for how the verdict feeds those decisions.

Consumers: gcp-to-aws (prose Generate) and heroku-to-aws (DSL Generate). The contract is source-agnostic; each caller wires the two touchpoints in its own Generate idiom — gcp-to-aws as prose steps, heroku-to-aws as a fragment step plus a fail-closed _postconditions assert enforced by the interpreter.

Part 1 — Authoring posture (load before writing terraform/)

Emit generated Terraform that satisfies the posture in references/security-posture-rules.md.

These are the "what good AWS Terraform looks like" rules. Following them makes the Part 2 gate pass by construction. This unit does not read the caller's artifacts — it consumes only caller-context signals the caller passes in.

Scope. security-posture-rules.md covers, in three tiers:

  • Gate-enforced (Part 2 verifies statically): ALB TLS, no-public-database, RDS + ElastiCache encryption-at-rest, no-public-DB-port ingress, no-public admin/datastore-port ingress, no-wildcard-IAM.

  • Authoring-only (not gate-checkable, still required): deletion_protection, master-password-via-Secrets-Manager, S3 hardening, Fargate/EKS/ECR settings, private-subnet placement, backups, baseline monitoring.

  • Compliance-conditional (emitted when the caller declares soc2/pci/hipaa/fedramp): VPC flow logs, S3 access logging, secret rotation, customer-managed KMS.

Still the caller's own generation concern (candidates to migrate here later): the account-hardening baseline.tf layer (CloudTrail, GuardDuty, Config, Security Hub).

Part 2 — Policy gate (run after writing terraform/)

Run the read-only checker against the generated directory. Resolve the script path relative to the plugin root ($PLUGIN_ROOT/skills/tf-best-practices/scripts/...), the same convention the plugin uses for its other scripts:

python3 "$PLUGIN_ROOT/skills/tf-best-practices/scripts/validate-terraform-policy.py" "$TERRAFORM_DIR" --json "$VERDICT_PATH"
  • $TERRAFORM_DIR — required, caller-supplied: the generated terraform/ directory (e.g. $MIGRATION_DIR/terraform). This skill never defaults or discovers it — the caller always passes the path it wrote Terraform to.

  • --json $VERDICT_PATH — optional; writes a machine-readable verdict the caller can merge into its own validation-report.json.

The policy check is one stage of a larger validation flow (fmt → init → validate → policy). The full protocol — including offline-fallback behavior and how the policy verdict maps into a validation-report.json — is documented in references/terraform-validation.md. That protocol is descriptive: the caller owns the fmt/init/validate execution, the fix-and-retry loop, and the report write; this unit contributes only the read-only policy stage + verdict shape.

Before infrastructure completion, the caller must run scripts/validate-terraform-report.py on the saved validation-report.json and require exit 0. The checker enforces the shared v2 completion contract. Its RUNTIME_REPORT_OK result does not establish that Terraform ran or passed.

Exit codes → caller action
ExitstdoutMeaningCaller does
0POLICY_OKposture satisfiedproceed
1POLICY_FAILviolations presentread violations[], edit the named .tf sites, re-run (caller's retry budget)
2(usage error)bad path / IOsurface to user; do not treat as pass
Verdict shape (--json)
{
  "check": "policy",
  "policy_status": "POLICY_OK | POLICY_FAIL",
  "violations": [
    {
      "check": "policy",
      "rule": "alb_https_listener | alb_http_redirect | no_tf_files",
      "file": "compute.tf",
      "line": 7,
      "severity": "error",
      "summary": "human-readable violation",
      "fix_hint": "concrete remediation the caller can apply"
    }
  ]
}

Each violations[] entry is actionable evidence — file + line + fix_hint tell the caller exactly what to edit. The caller applies the edit; this unit only reports.

Policy rules enforced today

Companion checks for migration artifacts

Migration callers can also run the shared read-only scripts/validate-migration-artifacts.py against their complete migration directory:

python3 "$PLUGIN_ROOT/skills/tf-best-practices/scripts/validate-migration-artifacts.py" \
  "$MIGRATION_DIR" --json "$MIGRATION_DIR/artifact-validation-status.json"

This produces ARTIFACTS_OK, ARTIFACTS_FAIL, or ARTIFACTS_ERROR, separately from the Terraform policy verdict. The caller must inspect the real exit code and report; it must not synthesize success. Supported checks cover PostgreSQL verification control flow, EB/database security-group wiring, GitHub Actions step references and deployment operations, and literal RDS time windows. Unsupported structures require review. This is not a general Bash safety proof, provider validation, or proof that a deployment succeeds.

Heroku callers add --require-postgres-script when PostgreSQL is in the design, and --require-eb-workflow when GitHub Actions is the selected EB deployment method. Other callers must not impose those Heroku-specific requirements. The checker never executes a generated migration script or changes input files or phase state; only the explicit JSON report path may be written.

For RDS/Aurora generation, scripts/rds_windows.py resolves independent daily backup and weekly maintenance windows from caller preferences. It rejects invalid or explicitly conflicting choices rather than silently changing them. Callers use its actual JSON values when authoring Terraform.

Terraform policy rules

Every rule is fail-open on ambiguity — it fires only on unambiguous, in-block literal evidence, so a valid stack is never falsely blocked (a POLICY_FAIL is a hard completion gate for the caller, so a false positive would block a real migration).

Internet-facing ALB TLS posture (an ALB is internet-facing when internal is absent, false, or variable-driven — fail-safe):

  • alb_https_listener — must have an HTTPS listener on 443 with certificate_arn and a forward action.

  • alb_http_redirect — an HTTP :80 listener must redirect to HTTPS, never forward to targets. Internal ALBs (internal = true) are exempt.

Elastic Beanstalk ALBs are invisible to these rules. The ALB rules inspect standalone aws_lb_listener blocks. An EB LoadBalanced environment provisions its ALB from aws_elastic_beanstalk_environment setting blocks, which the static checker does not read — so a pure-EB design passes the ALB rules vacuously (no listener to inspect). EB listener/TLS posture is therefore authoring-only, not gate-enforced. (Fixtures good-heroku-eb-only and good-heroku-eb-singleinstance document this; good-heroku-eb-loadbalanced carries a standalone ALB so the listener rules are exercised on real blocks.)

Managed database exposure & encryption (aws_db_instance, aws_rds_cluster):

  • rds_not_public — must not set publicly_accessible = true (absent/variable → fail-open).

  • rds_encryption_at_rest — must set storage_encrypted = true; missing or literal false fires (RDS defaults to unencrypted), variable-driven fails open. S3 is not checked (default SSE-S3 since Jan 2023).

ElastiCache encryption (aws_elasticache_replication_group, Redis aws_elasticache_cluster):

  • elasticache_encryption_at_rest — a replication group must set at_rest_encryption_enabled = true; missing or literal false fires, variable-driven fails open.

  • elasticache_cluster_encryption — a Redis-engine aws_elasticache_cluster (single-node: engine = "redis", no replication_group_id) must set BOTH at_rest_encryption_enabled = true and transit_encryption_enabled = true; missing or literal false on either fires, variable-driven fails open. engine = "memcached" clusters (and variable-driven/absent engine) are exempt — Memcached does not support these attributes.

Security group ingress:

  • db_sg_no_public_ingress — an inline aws_security_group ingress covering 5432/3306 must not allow 0.0.0.0/0 or ::/0.

  • sg_no_public_admin_ingress — an inline ingress must not open a curated never-public admin/datastore port (22, 3389, 6379, 11211, 27017, 9200/9300, 5601) to 0.0.0.0/0 or ::/0. Web (80/443) and app/game ports are not flagged; DB ports are handled by the rule above. Both check cidr_blocks and ipv6_cidr_blocks independently, so a benign IPv4 list does not mask an open IPv6 one. Both: separate aws_security_group_rule / aws_vpc_security_group_ingress_rule resources fail open (not correlated).

IAM least-privilege (aws_iam_policy, aws_iam_role_policy, aws_iam_group_policy, aws_iam_user_policy):

  • no_wildcard_iam — an Allow statement must not use Action/Resource "*". The one narrow exception is an isolated elasticbeanstalk:CreateStorageLocation statement with Resource = "*" because AWS does not support resource-level permissions for that action. aws_iam_policy_document data sources and assume-role trust policies fail open.

The checker is a zero-dependency static HCL reader (no terraform init, no provider download) — it runs even when the registry is unreachable. It uses brace-depth matching for nested blocks, so a valid HTTPS listener written with a nested forward { ... } block is not a false failure.

Fixtures (also the checker's regression suite)

fixtures/terraform-policy/ holds intentionally-shaped Terraform used by scripts/test_validate_terraform_policy.py:

  • bad-http-forward/ — internet-facing ALB that forwards plaintext HTTP → MUST POLICY_FAIL.

  • internal-alb-only/ — internal ALB on HTTP → MUST POLICY_OK (HTTP allowed internally).

  • good-https-redirect/ — the correct pattern → POLICY_OK.

These are deliberately non-compliant test data (never deployed). They are excluded from the repo-wide checkov scan via .checkov.yaml skip-path; do not "harden" them — doing so breaks the tests that assert the failure paths.

Verification

# from skills/tf-best-practices/
uv run --python 3.12 --with pytest python -m pytest scripts/test_validate_terraform_policy.py -q

Files

references/security-posture-rules.md

Generated-IaC Security Posture Rules

Cross-cutting security posture that generated AWS Terraform must follow, regardless of the source cloud (GCP, Heroku, …). These are authoring rules — "what good AWS Terraform looks like." Load this file before writing terraform/; emit resources that satisfy it.

Source-agnostic by design. Every rule here is a statement about AWS Terraform only. This file contains no GCP/Heroku/source-cloud logic — the consuming skill (the caller) owns all source-specific concerns and passes the caller-context signals a rule needs (see below).

Rule categories

  • Gate-enforced — the read-only policy gate (scripts/validate-terraform-policy.py) statically verifies these after generation: ALB TLS, no-public-database, RDS + ElastiCache encryption-at-rest, no-public-DB-port ingress, no-public admin/datastore-port ingress, no-wildcard-IAM. Each is fail-open on ambiguity — fires only on unambiguous in-block literal evidence, so a valid stack is never falsely blocked.

  • Authoring-only — best-practice rules the static gate cannot check but the caller must still emit: deletion_protection, the master-password-via-Secrets-Manager recipe, S3 hardening, EKS/ECR settings, private-subnet placement, backups, and the compliance-conditional emissions below. Not gate-blocked; still required for well-formed output.

Caller-context signals

A few rules are conditional on facts only the caller knows. The caller passes these when it loads this file; the rules reference them abstractly (never a source-cloud artifact):

  • compliance — the set of declared compliance frameworks (soc2, pci, hipaa, fedramp), or empty. Gates the Compliance-conditional emissions section. The caller derives this from its own requirements gathering and supplies the value; this file only says "if compliance includes X, emit Y."

  • aws_config values (instance classes, CPU/memory, sizes) — the caller reads these from its own design artifact and populates resource attributes; the posture rules constrain the shape, not the specific numbers.

The caller also owns any source-cloud detection (e.g. mapping a public-ingress finding from the source infra into a warning) — that logic never lives here.

Internet-facing ALB — TLS termination and HTTP redirect

Applies when: an aws_lb is an internet-facing Application load balancer — internal = false, omitted, or variable-driven (treated as internet-facing, fail-safe). Exempt: internal ALBs (internal = true), and Network (L4) / Gateway (L3) load balancers (load_balancer_type = "network" or "gateway") — these front raw TCP/UDP and legitimately have no HTTPS:443 listener.

Rules:

  1. Emit an HTTPS listener on port 443 (protocol = "HTTPS") with a modern ssl_policy, a certificate_arn, and a forward default action to the app target group.

  2. Emit an HTTP listener on port 80 whose default action is a redirect to HTTPS (HTTP_301) — never a forward to targets.

  3. The ALB security group allows 443 from the internet and 80 only for the redirect; never forward plaintext HTTP to targets. Target groups may use HTTP to the tasks behind the ALB — TLS terminates at the ALB.

Reference HCL (emit whenever aws_lb is internet-facing):

resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.app.arn
  port              = 443
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  certificate_arn   = var.acm_certificate_arn

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.app.arn
  }
}

resource "aws_lb_listener" "http_redirect" {
  load_balancer_arn = aws_lb.app.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type = "redirect"
    redirect {
      port        = "443"
      protocol    = "HTTPS"
      status_code = "HTTP_301"
    }
  }
}

variable "acm_certificate_arn" {
  description = "ACM certificate ARN for the public ALB HTTPS listener"
  type        = string
  # TODO: request or import a certificate for your app domain
}

Gate mapping: rule 1 → alb_https_listener; rule 2 → alb_http_redirect (see scripts/validate-terraform-policy.py). If generated Terraform lacks the HTTPS listener or forwards HTTP, that is a generation defect the caller must fix — not a reason to draw or ship plaintext HTTP.

Managed database — no public exposure

Applies to: aws_db_instance, aws_rds_cluster.

Rules:

  1. Never emit publicly_accessible = true. Place the database in private subnets and reach it from application security groups only. RDS defaults to false, so simply omitting the attribute is compliant.

  2. Emit storage_encrypted = true — RDS storage defaults to unencrypted, so this must be explicit. Optionally set kms_key_id for a customer-managed key.

Gate mapping: rule 1 → rds_not_public; rule 2 → rds_encryption_at_rest. The gate fires only on a literal publicly_accessible = true / missing-or-false storage_encrypted; a variable-driven value fails open (not flagged). S3 is not checked — buckets have default SSE-S3 since Jan 2023, so a missing SSE block is not an unencrypted bucket.

ElastiCache — encryption

Applies to: aws_elasticache_replication_group and Redis-engine aws_elasticache_cluster.

Rule:

  • aws_elasticache_replication_group: set at_rest_encryption_enabled = true (and consider transit_encryption_enabled = true). ElastiCache does not encrypt at rest by default.

  • aws_elasticache_cluster in the Redis single-node form (engine = "redis", no replication_group_id): MUST set transit_encryption_enabled = true. Note that at_rest_encryption_enabled is NOT a valid argument on aws_elasticache_cluster (AWS provider schema) — at-rest encryption requires an aws_elasticache_replication_group. So the cluster form is gated on transit encryption; when at-rest is needed, emit a replication group instead. (This does NOT prescribe cluster-vs-replication-group for HA — that choice is deferred; when the cluster form is emitted, it must set transit encryption.)

  • engine = "memcached" clusters remain exempt — Memcached does not support these attributes.

Gate mapping: elasticache_encryption_at_rest (replication group) and elasticache_cluster_encryption (Redis cluster). Both fire on missing-or-false; variable-driven values (and a variable-driven or absent engine) fail open. A Memcached aws_elasticache_cluster is exempt.

Database security group — no public ingress on DB ports

Applies to: inline ingress { ... } blocks inside aws_security_group.

Rule: an ingress rule covering a database port (5432 PostgreSQL, 3306 MySQL) must not allow 0.0.0.0/0 (in cidr_blocks) or ::/0 (in ipv6_cidr_blocks). Restrict to the application security group (security_groups = [...]) or a private CIDR.

Gate mapping: db_sg_no_public_ingress. The gate inspects only inline ingress blocks; separate aws_security_group_rule / aws_vpc_security_group_ingress_rule resources fail open (the static reader cannot correlate them to their security group), so prefer inline ingress where you want gate coverage.

Security group — no public admin / datastore ports

Applies to: inline ingress { ... } blocks inside aws_security_group.

Rule: an ingress rule must not open a well-known admin or datastore port to 0.0.0.0/0 or ::/0. The enforced set is deliberately fixed to ports that are ~never legitimately public: 22 (SSH), 3389 (RDP), 6379 (Redis), 11211 (Memcached), 27017 (MongoDB), 9200/9300 (Elasticsearch), 5601 (Kibana). Reach these from a bastion/app security group or a private CIDR instead.

Gate mapping: sg_no_public_admin_ingress. Web ports (80/443) and application/game ports (e.g. high ranges) are not flagged — the rule targets a curated never-public list, not "any public ingress", so legitimately-public workloads pass. Database ports (5432/3306) are handled by db_sg_no_public_ingress and excluded here to avoid double-reporting. Same inline-only fail-open scope as that rule.

Both security-group gates read cidr_blocks and ipv6_cidr_blocks as separate attributes and check each family's "entire internet" range. On dual-stack and IPv6-only VPCs, ::/0 on an admin or database port is exactly as exposed as 0.0.0.0/0, so a benign IPv4 list does not excuse an open IPv6 list. The violation message names the range that actually fired.

Ranges are compared after canonicalisation, not as text: ::/0, ::0/0 and 0:0:0:0:0:0:0:0/0 are the same range and all fire. terraform fmt treats a CIDR as an opaque string, so nothing else normalises these — and IPv6 has many more legal spellings of the zero address than IPv4. Only quoted literals inside the list count, and comments are stripped first, so a range named only in a comment (# TODO: was 0.0.0.0/0) is not an allowed range and does not fire. Non-literal values (var.x, ${...}) remain fail-open as documented above.

IAM — no wildcard permissions

Applies to: aws_iam_policy, aws_iam_role_policy, aws_iam_group_policy, aws_iam_user_policy.

Rule: an Allow statement must not use a sole wildcard for Action or Resource, in either string form ("*") or single-element list form (["*"]). Scope to specific actions and resource ARNs. A list that also contains scoped entries (e.g. ["s3:GetObject", ...]) is not a blanket wildcard and is allowed.

The narrow exception is an isolated elasticbeanstalk:CreateStorageLocation statement with Resource = "*". AWS does not define resource-level permissions for that action; combining it with any other action does not qualify for the exception.

Gate mapping: no_wildcard_iam. The gate scans literal policy JSON (heredoc or jsonencode({...})) in the resources above. aws_iam_policy_document data sources fail open (their statements are HCL blocks, not literal JSON the reader can inspect), and assume-role trust policies on aws_iam_role are out of scope — so a scoped data-source policy is never falsely flagged.


Authoring-only rules (not gate-enforced)

The static gate cannot verify these, but well-formed AWS Terraform must still emit them. Apply them at authoring time alongside the gate-enforced rules above.

Database — durability & credential hygiene

Applies to: aws_db_instance, aws_rds_cluster and their supporting resources.

  1. deletion_protection = true by default. Add an inline comment: # Set to false only when intentionally destroying this cluster.

  2. Backups enabled (backup_retention_period > 0).

  3. Emit a DB subnet group + parameter group + security group; place the instance in private subnets.

  4. Never put a database password in a committed variable default or tfvars file. Prefer manage_master_user_password = true on the RDS instance/cluster when the application can consume its managed Secrets Manager secret. Otherwise generate and store the credential as below. A generated password and a Secrets Manager data source still put the secret value in Terraform state: protect the state backend and its access; do not describe this pattern as keeping passwords out of state.

    resource "random_password" "db_master" {
      length  = 32
      special = true
    }
    
    resource "aws_secretsmanager_secret" "db_master" {
      name = "${var.project_name}/rds/master-credentials"
    }
    
    resource "aws_secretsmanager_secret_version" "db_master" {
      secret_id     = aws_secretsmanager_secret.db_master.id
      secret_string = jsonencode({ password = random_password.db_master.result })
    }
    
    data "aws_secretsmanager_secret_version" "db_master" {
      secret_id  = aws_secretsmanager_secret.db_master.id
      depends_on = [aws_secretsmanager_secret_version.db_master]
    }
    
    # On aws_db_instance (RDS PostgreSQL/MySQL):
    #   password = jsondecode(data.aws_secretsmanager_secret_version.db_master.secret_string)["password"]
    # On aws_rds_cluster (Aurora):
    #   master_password = jsondecode(data.aws_secretsmanager_secret_version.db_master.secret_string)["password"]
    # Never emit master_password on aws_db_instance: the provider rejects it.
  5. Match the application secret to the database credential. When ECS injects a JSON Secrets Manager value into a scalar DB_PASSWORD, select its password key: valueFrom = "${aws_secretsmanager_secret.db_master.arn}:password::". For an RDS-managed credential use "${aws_db_instance.database.master_user_secret[0].secret_arn}:password::". The bare ARN injects the entire JSON document, not its password field. Keep the task execution role's secretsmanager:GetSecretValue permission scoped to that same secret (and kms:Decrypt to its customer-managed key when used). The host, port, database name, username, and secret must all describe the same database resource; never infer the relationship from similar labels. Fargate Linux JSON-key injection requires platform version 1.4.0 or later (or LATEST).

S3 — bucket hardening

Applies to: application aws_s3_bucket resources (not log-sink buckets, which have their own policies).

  1. Versioning enabled.

  2. Encryption: SSE-S3 or SSE-KMS (a bucket without an explicit SSE block still has default SSE-S3 since Jan 2023 — do not treat its absence as unencrypted, but prefer an explicit block).

  3. Block public access by default (account- and bucket-level).

  4. Lifecycle policies for cost/retention where applicable.

  5. If public content is required, front it with CloudFront + Origin Access Control (OAC) — never a public bucket policy.

Compute — Fargate / EKS / ECR

  1. Fargate tasks run in private subnets; size from the caller-supplied aws_config CPU/memory.

  2. EKS: default to a private API endpoint — endpoint_private_access = true, endpoint_public_access = false. Add a comment: # Public endpoint disabled. To enable kubectl access from outside the VPC set endpoint_public_access = true and restrict public_access_cidrs to known CIDRs.

  3. ECR: every aws_ecr_repository includes image_scanning_configuration { scan_on_push = true } (free basic scanning catches known CVEs before images reach production).

Networking — subnet & egress baseline

  1. Span at least 2 Availability Zones.

  2. Public + private subnets; workloads (compute, database) live in private subnets.

  3. NAT gateway for private-subnet outbound internet when required.

Monitoring — baseline observability

  1. A CloudWatch log group per service with a sane retention (default 30 days).

  2. A dashboard with key metrics. (Specific alarm thresholds come from the caller's context — the caller supplies success-metric targets; this rule constrains the shape, not the values.)


Compliance-conditional emissions

These are AWS best-practice hardening steps that apply only when the caller declares a compliance framework. The rule lives here; the trigger (the compliance set) is a caller-context signal (see Caller-context signals above) — the caller passes it in; this file never reads a source-cloud artifact.

Apply based on the caller-supplied compliance set:

Emit when compliance includes…Emit
pci, hipaa, or fedrampVPC flow logs — aws_flow_log for the VPC → a CloudWatch log group. Inline cost note: # VPC Flow Logs: ~$0.50/GB ingested. Enabled for compliance. Disable if cost is a concern and compliance posture allows.
pci, hipaa, or fedrampS3 access logging — aws_s3_bucket_logging for every application bucket → a dedicated access-log bucket. Inline cost note: # S3 access logging: ~$0.023/GB stored. Enabled for compliance. Disable if cost is a concern and compliance posture allows.
soc2, pci, hipaa, or fedrampSecret rotation — a companion aws_secretsmanager_secret_rotation (automatically_after_days = 30) for every aws_secretsmanager_secret, with a TODO comment for the rotation Lambda ARN.
pci, hipaa, or fedrampCustomer-managed KMS — an aws_kms_key referenced via kms_key_id on every aws_secretsmanager_secret (AWS-managed key is sufficient otherwise).

When compliance is empty, emit none of the above — keep the generated Terraform minimal and immediately applyable. (The account-hardening baseline.tf layer — CloudTrail, GuardDuty, Config, Security Hub — remains the caller's own generation concern for now; it is a candidate to migrate here later.)

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
AWS
Publisher
AWS (Official)
Source
aws/agent-toolkit-for-aws · plugins/aws-startup-advisor/skills/tf-best-practices · commit 0a218f8
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • NOTICE (added by AutoGineer from NOTICE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by AWS.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download tf-best-practices.zip