AWS Terraform のベストプラクティス(業界標準の望ましい実装方法)による作成ガイダンスと、移行スキルによって生成された Terraform のポリシーゲート(承認・検査機能)です。terraform/ ディレクトリへの書き込みが行われるあらゆる段階で読み込まれます。 まず「何を出力するか」という指針ルールとセキュリティの基準仕様として機能し、その後、実際に書き込んだ後の検証フェーズで確定的な検査結果を示します。 **読み取り専用です** — 生成された Terraform が基準を満たしているかを報告するだけで、.tf ファイルを編集したり、.phase-status.json に手を加えたり、フェーズの完了を判定することはありません。terraform fmt/init/validate といった既存ツールを補完する役割であり、これらに代わるものではありません。
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.
共有オーサリング(作成)ガイドと判定生成ツールです。ワークフロー(処理の流れ)ではなく、AWS Terraformを生成するフェーズ(段階)向けに2つの質問に答えます。
作成前 — 「生成される terraform/ が従うべきセキュリティポスチャー(基準)は何か?」
(ポスチャールール + baseline.tf アカウント強化仕様書)
作成後 — 「生成された terraform/ はポリシー(方針)に合格したか?」
(判定的で読み取り専用の判定結果 + 機械可読レポート)
このスキルは、呼び出し元のGenerate(生成)フローの2つのタッチポイント(接触地点)で使用され、その間に呼び出し元独自のTerraform作成作業が入ります。呼び出し元は読み込み時にどのタッチポイントであるかを指定し、対応する部分を読みます。
| 呼び出し元の状況 | 読み込む部分 | 理由 |
|---|---|---|
terraform/ を作成しようとしている(作成前) |
パート1 → references/security-posture-rules.md |
「何を出力するか」というAWSオーサリングルール(ゲート強制 + オーサリングのみ + コンプライアンス条件付き) |
terraform/ は作成済み、検証準備完了(作成後) |
パート2 → references/terraform-validation.md + ゲートスクリプト実行 |
fmt → init → validate → policy プロトコル(手順)と読み取り専用の判定結果 |
このスキルが述べるすべてはクラウドプロバイダに依存しない(純粋なAWS Terraform)です。GCP/Herokuの検出やアーティファクト(成果物)の読み取りは呼び出し元の責任です。ルールが呼び出し元の既知の事実(例:宣言されたコンプライアンスフレームワーク)を必要とする場合、呼び出し元は呼び出し元コンテキストシグナルとして渡します — references/security-posture-rules.md § 呼び出し元コンテキストシグナル を参照。
このユニットは判定生成ツールであり、決して変更ツールではありません。書き込み面全体は、出力を求められるJSON判定結果です。具体的には以下はしません。
.tf ファイルを編集、フォーマット、または書き直す(呼び出し元が修正を所有).phase-status.json または任意の実行状態ファイルを読み書きする(インタープリタが所有)呼び出し元(マイグレーションスキルのGenerateフェーズ)が所有するもの:生成した .tf を編集する修正と再試行ループ、terraform fmt 自動適用、再試行/スキップ/中止の促し、フェーズ完了ゲート、すべての .phase-status.json 書き込み。判定がそれらの決定にどう活用されるかは、使用するスキルのGenerate フェーズを参照してください。
利用者(v1):
gcp-to-awsのみ。契約はソースに依存せず、後でheroku-to-awsに採用される設計ですが、その配線は今のところ意図的に対象外です。
terraform/ を作成する前に読み込む)references/security-posture-rules.md のポスチャーを満たす生成Terraformを出力します。
これらは「良いAWS Terraformとは何か」というルールです。これらに従うと、パート2のゲートは構造上合格します。このユニットは呼び出し元のアーティファクトを読みません — 呼び出し元が渡す呼び出し元コンテキストシグナルのみを使用します。
範囲。
security-posture-rules.mdは3つの階層で対応します。
- ゲート強制(パート2が静的に検証):ALB TLS、パブリックデータベース禁止、RDS + ElastiCache保存時暗号化、パブリックDB ポート侵入禁止、パブリック管理/データストアポート侵入禁止、ワイルドカードIAM禁止
- オーサリングのみ(ゲートチェック不可、必須):
deletion_protection、マスターパスワード(Secrets Managerを経由)、S3強化、Fargate/EKS/ECR設定、プライベートサブネット配置、バックアップ、ベースラインモニタリング- コンプライアンス条件付き(呼び出し元が
soc2/pci/hipaa/fedrampを宣言した場合に出力):VPCフロー ログ、S3アクセスログ、シークレットローテーション、顧客管理KMSまだ呼び出し元独自の生成関心事(後で移行する候補):アカウント強化
baseline.tfレイヤー(CloudTrail、GuardDuty、Config、Security Hub)
terraform/ を作成した後に実行)生成されたディレクトリに対して読み取り専用チェッカーを実行します。スクリプトパスをプラグインルートを基準に解決します(プラグインが他のスクリプトに使用する同じ規則)。
python3 "$PLUGIN_ROOT/skills/tf-best-practices/scripts/validate-terraform-policy.py" "$TERRAFORM_DIR" --json "$VERDICT_PATH"
$TERRAFORM_DIR — 必須、呼び出し元供給:生成された terraform/ ディレクトリ(例:$MIGRATION_DIR/terraform)。このスキルはデフォルト値を設定したり、発見したりしません — 呼び出し元は常にTerraformを書いたパスを渡します。--json $VERDICT_PATH — オプション。呼び出し元が独自の validation-report.json にマージできる機械可読判定を書き込みます。ポリシーチェックは、より大きな検証フロー(fmt → init → validate → policy)の1段階です。完全なプロトコル — オフラインフォールバック動作やポリシー判定が validation-report.json にどうマップされるか含む — は references/terraform-validation.md に記載されています。そのプロトコルは記述的です。呼び出し元がfmt/init/validate実行、修正と再試行ループ、レポート書き込みを所有し、このユニットは読み取り専用ポリシー段階 + 判定形状のみを提供します。
| 終了コード | 標準出力 | 意味 | 呼び出し元がすること |
|---|---|---|---|
0 |
POLICY_OK |
ポスチャー(基準)満たし | 進める |
1 |
POLICY_FAIL |
違反あり | violations[] を読む、指定された .tf サイトを編集、再実行(呼び出し元の再試行予算範囲内) |
2 |
(使用方法エラー) | パス/IO不良 | ユーザーに表示;合格として扱わない |
--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": "人間が読める違反説明",
"fix_hint": "呼び出し元が適用できる具体的な修正方法"
}
]
}
各 violations[] エントリは実行可能な証拠です — file + line + fix_hint は、呼び出し元が何を編集すべきかを正確に伝えます。呼び出し元が編集を適用します。このユニットは報告するのみ。
すべてのルールは曖昧性でフェイルオープンです — 曖昧でない、ブロック内の明白な証拠でのみ発火するため、有効なスタックが誤ってブロックされません(POLICY_FAIL は呼び出し元の完了の厳密なゲートなので、誤検知は実際のマイグレーションをブロックします)。
インターネット公開ALB TLSポスチャー(ALBはインターネット公開。internal が不在、false、または変数駆動の場合 — フェイルセーフ):
alb_https_listener — 443 に certificate_arn と forward アクション付きのHTTPSリスナーが必須。alb_http_redirect — HTTP :80 リスナーは、ターゲットに forward ではなくHTTPSに redirect 必須。内部ALB(internal = true)は免除。マネージドデータベース露出 & 暗号化(aws_db_instance、aws_rds_cluster):
rds_not_public — publicly_accessible = true を設定してはいけない(不在/変数 → フェイルオープン)。rds_encryption_at_rest — storage_encrypted = true を設定必須;欠落または明白な false は発火(RDSはデフォルト暗号化なし)、変数駆動はフェイルオープン。S3は未チェック(2023年1月以降デフォルトSSE-S3)。ElastiCache暗号化(aws_elasticache_replication_group):
elasticache_encryption_at_rest — at_rest_encryption_enabled = true を設定必須;欠落または明白な false は発火、変数駆動はフェイルオープン。aws_elasticache_cluster(Memcached)は未チェック。セキュリティグループ侵入:
db_sg_no_public_ingress — 5432/3306 をカバーするインライン aws_security_group 侵入は、0.0.0.0/0 または ::/0 を許可してはいけない。sg_no_public_admin_ingress — インライン侵入は、選別されたパブリック禁止ポート(22、3389、6379、11211、27017、9200/9300、5601)をパブリック(0.0.0.0/0 または ::/0)に開いてはいけない。Web(80/443)およびアプリ/ゲームポートはフラグ立てなし;DBポートは上記ルールで処理。双方 cidr_blocks と ipv6_cidr_blocks を独立して確認するため、良好なIPv4リストがオープンなIPv6をマスクしません。双方:個別 aws_security_group_rule / aws_vpc_security_group_ingress_rule リソースはフェイルオープン(相関なし)。IAM最小権限(aws_iam_policy、aws_iam_role_policy、aws_iam_group_policy、aws_iam_user_policy):
no_wildcard_iam — Allow ステートメント(声明)は Action/Resource に "*" を使用してはいけない。aws_iam_policy_document データソースと仮定ロール信頼ポリシーはフェイルオープン。チェッカーはゼロ依存関係の静的HCLリーダー(
terraform initなし、プロバイダダウンロードなし)です — レジストリに到達不可能でも実行されます。ネストされたブロックに対して括弧深さマッチングを使用するため、ネストされたforward { ... }ブロックで記述された有効なHTTPSリスナーは偽検知ではありません。
fixtures/terraform-policy/ は 意図的に成形された Terraform を保有し、scripts/test_validate_terraform_policy.py が使用します:
bad-http-forward/ — インターネット公開ALBが平文HTTP転送 → POLICY_FAIL 必須。internal-alb-only/ — HTTP上の内部ALB → `A shared authoring guide and verdict producer, not a workflow. It answers two questions for a phase that generates AWS Terraform:
terraform/ follow?"
(the posture rules + the baseline.tf account-hardening spec)terraform/ pass policy?" (a deterministic,
read-only verdict + a machine-readable report)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 context | Load | Why |
|---|---|---|
About to author terraform/ (before writing) |
Part 1 → references/security-posture-rules.md |
The "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 script |
The 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.
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:
.tf file (the caller owns remediation),.phase-status.json or any run-state file (interpreter-owned),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 (v1):
gcp-to-awsonly. The contract is source-agnostic and designed to be adopted byheroku-to-awslater, but that wiring is intentionally out of scope for now.
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.mdcovers, 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.tflayer (CloudTrail, GuardDuty, Config, Security Hub).
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.
| Exit | stdout | Meaning | Caller does |
|---|---|---|---|
0 |
POLICY_OK |
posture satisfied | proceed |
1 |
POLICY_FAIL |
violations present | read violations[], edit the named .tf sites, re-run (caller's retry budget) |
2 |
(usage error) | bad path / IO | surface to user; do not treat as pass |
--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.
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.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):
elasticache_encryption_at_rest — must set at_rest_encryption_enabled = true; missing
or literal false fires, variable-driven fails open. aws_elasticache_cluster (Memcached)
not checked.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 "*".
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 nestedforward { ... }block is not a false failure.
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.
# from skills/tf-best-practices/
uv run --python 3.12 --with pytest python -m pytest scripts/test_validate_terraform_policy.py -q
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。