Claude Code - SuperClaude を使って Terraform 書いてみた
こんにちは。
ご機嫌いかがでしょうか。
"No human labor is no human error" が大好きな吉井 亮です。
VibeCoding/VibeOps を極めるべく、Terraform も Coding Agent に書いてもらうと考えています。
試行錯誤しながら最適な方法を模索しているところです。
今回は Claude Code & SuperClaude を使って Terraform コードを書いてみました。
SuperClaude
Claude Code を拡張する強力なフレームワークです。
本来はアプリケーション開発に強みを発揮するはずなので、開発者の方も興味があればぜひ試してみてください。
インストール方法は上の公式リポジトリを参照ください。
私はプロジェクトリポジトリに置いて、複数人で同じ SuperClaude 環境を使いたかったので上のインストール後にファイルをリポジトリ配下へ手動コピーしています。
コピー後は以下のようになってます。
.claude
├── CLAUDE.md
├── commands
│ ├── __init__.py
│ ├── analyze.md
│ ├── build.md
│ ├── cleanup.md
│ ├── design.md
│ ├── document.md
│ ├── estimate.md
│ ├── explain.md
│ ├── git.md
│ ├── implement.md
│ ├── improve.md
│ ├── index.md
│ ├── load.md
│ ├── spawn.md
│ ├── task.md
│ ├── test.md
│ ├── troubleshoot.md
│ └── workflow.md
├── COMMANDS.md
├── FLAGS.md
├── hooks
│ ├── __init__.py
│ └── PLACEHOLDER.py
├── MCP.md
├── MODES.md
├── ORCHESTRATOR.md
├── PERSONAS.md
├── PRINCIPLES.md
├── RULES.md
└── settings.local.json
mcp.json
オリジナルでは Playwright や Magic を使っていますが、IaC では不要だと思っているので、それらは除いています。
Terraform を使うので awslabs.terraform-mcp-server
を追加しています。これがもう便利で、AWS リソースを作成する際には欠かせません。
{
"mcpServers": {
"awslabs.aws-documentation-mcp-server": {
"command": "uvx",
"args": [
"awslabs.aws-documentation-mcp-server@latest"
],
"env": {
"FASTMCP_LOG_LEVEL": "ERROR",
"AWS_DOCUMENTATION_PARTITION": "aws"
},
"disabled": false,
"autoApprove": []
},
"awslabs.terraform-mcp-server": {
"command": "uvx",
"args": [
"awslabs.terraform-mcp-server@latest"
],
"env": {
"FASTMCP_LOG_LEVEL": "ERROR"
},
"disabled": false,
"autoApprove": []
},
"Context7": {
"command": "npx",
"args": [
"-y",
"@upstash/context7-mcp"
]
},
"sequential-thinking": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-sequential-thinking"
]
}
}
}
MCP.md
MCP Server を追加したので、.claude/MCP.md
にそれらの説明を追記します。
## AWS Documentation Integration (Official AWS Docs)
**Purpose**: Authoritative AWS service documentation lookups, examples, API semantics, limits, and best practices using the awslabs.aws-documentation-mcp-server.
**Activation Patterns**:
- Automatic: AWS service/resource names detected (e.g., S3, IAM, EKS), IaC referencing AWS resources, cloud architecture questions
- Manual: `--aws-docs`, `--awsdocs`, `/docs aws <topic>` flags
- Smart: When an answer must cite official AWS docs or clarify version/partition specifics
**Workflow Process**:
1. Topic Detection: Identify AWS service and specific concept (feature, quota, API, example)
2. Search: Query AWS documentation for the topic (high-relevance results first)
3. Read: Fetch and convert the selected page to markdown for citation and pattern extraction
4. Explore Related: Pull recommendations for adjacent or commonly-followed pages
5. Pattern Extraction: Extract steps, code samples, configuration blocks
6. Validation: Align implementation with official guidance and note constraints/quotas
7. Caching: Store key references for reuse in the session
**Primary Operations**:
- Search AWS Docs: Targeted search across AWS documentation corpus
- Read Page: Retrieve full page content (markdown), with chunking for long documents
- Recommend: Related/highly-rated/similar/journey pages for broader context
**Error Recovery**:
- Domain/URL constraints → Re-scope search terms or fallback to cached knowledge
- Truncated long pages → Continue reading with next chunk index
- Partition differences → Respect configured partition (env: `AWS_DOCUMENTATION_PARTITION`)
- Server unavailable → Graceful degradation with known patterns; note limitations
## Terraform Integration (AWS IaC Research & Validation)
**Purpose**: Terraform/Terragrunt research, provider/resource docs lookup, module discovery, and security scanning guidance using the awslabs.terraform-mcp-server.
**Activation Patterns**:
- Automatic: Terraform files detected (`.tf`, Terragrunt), provider/resource questions, IaC review requests
- Manual: `--tf`, `--terraform`, `/tf <action>` flags
- Smart: When selecting modules, comparing resources, or planning security scans
**Workflow Process**:
1. Resource Identification: Detect providers (AWS/AWSCC) and resources/data sources in question
2. Provider Docs: Retrieve AWS Provider or AWS Cloud Control (AWSCC) docs for arguments, attributes, and examples
3. Module Discovery: Search AWS-IA curated modules and user-provided registry modules; enumerate inputs/outputs
4. Security Scan Planning: Prepare Checkov rules of interest and expected failure classes
5. Execution Assistance: Outline safe `init/plan/apply/destroy` or Terragrunt equivalents with state/backends
6. Synthesis: Summarize compatibility notes, version pins, deprecations, and migration paths
7. Caching: Keep frequently-used resources/modules for quick reuse
**Capabilities**:
- Terraform Commands: init/plan/apply/destroy (with careful, opt-in execution guidance)
- Terragrunt Commands: orchestration over multiple modules
- Security: Checkov scan planning and interpretation of common findings
- Docs Lookup: AWS Provider and AWSCC resource/data source docs
- Module Search: AWS-IA curated modules and arbitrary registry modules, with IO summary
**Error Recovery**:
- Version mismatch (provider/module) → Suggest compatible versions or upgrade/downgrade paths
- Module not found/insufficient docs → Propose closest alternatives; escalate to provider docs
- Init/lock/state errors → Recommend backend/state remediation steps (without destructive actions)
- Scan timeouts → Retry with scoped directories/rule sets; provide partial results
PERSONA.md
.claude/PERSONA.md
にペルソナが定義されています。
--persona-devops
の MCP Server 部分を少し修正します。awslabs.aws-documentation-mcp-server
と awslabs.terraform-mcp-server
を優先的に使ってもらえるようにしました。
このペルソナが SuperClaude を使う利点のうちの一つです。
## `--persona-devops`
**Identity**: Infrastructure specialist, deployment expert, reliability engineer
**Priority Hierarchy**: Automation > observability > reliability > scalability > manual processes
**Core Principles**:
1. **Infrastructure as Code**: All infrastructure should be version-controlled and automated
2. **Observability by Default**: Implement monitoring, logging, and alerting from the start
3. **Reliability Engineering**: Design for failure and automated recovery
**Infrastructure Automation Strategy**:
- **Deployment Automation**: Zero-downtime deployments with automated rollback
- **Configuration Management**: Infrastructure as code with version control
- **Monitoring Integration**: Automated monitoring and alerting setup
- **Scaling Policies**: Automated scaling based on performance metrics
**MCP Server Preferences**:
- **Primary**: aws-doc - For aws best practices
- **Secondary**: terraform - For code-base architectural analysis and infrastructure patterns
- **Tertiary**: Sequential - For comprehensive architectural analysis
- **Quaternary**: Context7 - For architectural patterns and best practices
**Optimized Commands**:
- `/git` - Version control workflows and deployment coordination
- `/analyze --focus infrastructure` - Infrastructure analysis and optimization
**Auto-Activation Triggers**:
- Keywords: "deploy", "infrastructure", "automation"
- Deployment or infrastructure work
- Monitoring or observability mentioned
**Quality Standards**:
- **Automation**: Prefer automated solutions over manual processes
- **Observability**: Implement comprehensive monitoring and alerting
- **Reliability**: Design for failure and automated recovery
CLAUDE.md
.claude/CLAUDE.md
を更新します。RULES.md
とかに書いたほうが良さそうですが、今は気にしないことにします。
プロジェクトによっては積み重ねてきた秘伝のルールがあると思います。(下の例は生成 AI に作ってもらいましたが…)
---
title: CLAUDE.md
created_at: 2025-07-29 09:08:00
updated_at: 2025-08-12 16:43:00
---
# CLAUDE.md
## SuperClaude Entry Point
@COMMANDS.md
@FLAGS.md
@PRINCIPLES.md
@RULES.md
@MCP.md
@PERSONAS.md
@ORCHESTRATOR.md
@MODES.md
## 技術スタック
terraform
## Terraform モジュール
- モジュールは再利用可能な形式で作成する
- Terraform リソースに必要な設定値はすべて変数とする
- 出力は必ず定義し、必要に応じて他のモジュールで利用できるようにする
- 必須ではない設定項目は Dynamic Blocks を使って動的に構成する
モジュールのディレクトリ構成は以下とする。
- Terraform リソース名
- `README.md`: モジュールの使い方や注意点を記載
- `main.tf`: リソースの定義
- `variables.tf`: 変数の定義
- `outputs.tf`: 出力の定義
例)
└── modules
├── iam_role
├── README.md
├── main.tf
├── variables.tf
└── outputs.tf
## Terraform 命名規約
Terraform 構成の可読性と保守性向上のため、以下の命名規約を採用する。
- 総則
- 小文字スネークケース(a-z, 0-9, アンダースコア)。先頭は英字。ハイフンは使わない。
- 意味のある名詞を用い、タイプ名や冗長な接頭辞は入れない(例: "aws_instance" のリソース名に "aws" や "instance" を含めない)。
- 環境・領域などの属性は接尾辞で表現(例: `_prod`, `_stg`, `_dev`)。
- リソース(resource)
- 形式: `resource "<provider>_<type>" "<name>" { ... }`
- `<name>` は機能/役割を表す名詞(例: `web_api`, `bastion`, `app_lb`)。
- `for_each` 使用時はキーの一意性を担保し、`each.key` を名前やタグに反映。
- ネスト順序: メタ引数 → 引数 → ネストブロック → メタ引数ブロック(`lifecycle` など)は最後。
- データソース(data)
- 依存されるデータソースは、参照するリソースより上に配置。
- 名称は取得対象を表す名詞(例: `ami_web`, `az_available`)。
- 変数(variable)
- `locals` を利用、`variables` はモジュールでのみ使用。
- type, description を必須記載
- ブール値は `enable_`/`disable_` より `enable_` を推奨(例: `enable_public_access`)。
- 数量は単数名(例: `instance_count`)、リスト/マップは内容が分かる複数名(例: `subnet_ids`, `tags`)。
- 機密は `sensitive = true` を明示。
- ローカル(locals)
- 再利用する式/共通プレフィックスやサフィックスを表現(例: `name_suffix`, `tags_common`)。
- 変数やローカルの過剰使用は避け、読みやすさを優先。
- 出力(output)
- 名称は内容を反映(例: `web_public_ip`, `vpc_id`)。
- `description` を必ず記載。秘匿情報の出力は禁止。
- モジュール(module)
- モジュール名は機能単位(例: `vpc`, `subnets`, `iam_role`)。
- 入出力は上記の variable/output 規約に従う。
- プロバイダエイリアスを渡す場合は `providers` ブロックで明示(例: `aws = aws.west`)。
- プロバイダ(provider)
- デフォルト設定を必ず用意。複数リージョン/アカウントは `alias` を短く意味のある名で(例: `aws.west`, `aws.audit`)。
- ディレクトリ/ファイル
- 共有・再利用コードは `modules/` 配下に置く。環境で分ける場合は環境ディレクトリで state/backend/vars を分離。
- タグ/Name 命名(AWS 例)
- 最低限: `Name`, `Environment`。
- `Name` は `<system>-<component>-<env>[-<suffix>]` を推奨(例: `peg-api-stg-01`)。
- タグ値生成はローカルで統一(例: `local.tags_common`)。
- Do / Don't 例
- ✅ `resource "aws_instance" "web_api" { ... }`
- ❌ `resource aws_instance webAPI-aws-instance { ... }`(クォート/スネークケース/タイプ重複の違反)
- ✅ `variable "db_password" { sensitive = true }`
- ✅ `output "web_public_ip" { description = "Public IP of web" }`
- ポリシー記述方法
- `jsonencode()` を使用してポリシーを記述する
- 禁止行為
- `count` は使用しない。代わりに `for_each` を使用する。
- 参考(社内運用の基準)
- コミット前に `terraform fmt` と `terraform validate` を実施。
- 大量作成は `for_each` を優先し、キーは安定的で衝突しない値を採用。
- ワークスペース/環境名は一貫した接尾辞(例: `-dev`, `-stg`, `-prod`)を用いる。
## ファイル中の説明文
説明文は日本語で記述すること。
指示書
上までで SuperClaude の準備は完了です。
今回は GitHub Actions で使う OIDC ロールを作成するための指示書を作成します。プロジェクトがこれから始まるといった感じですね!
別のプロジェクトで使ったコードをコピーしたほうが早いだろ、というツッコミは軽く流しておいてやっていきます。
下のファイルを todos/oidc_github.md
として作成します。
---
title: GitHub OIDC ロール
created_at: 2025-08-12 15:13:00
updated_at: 2025-08-12 15:13:00
---
# タスク
GitHub Actions から AWS へ OIDC ロールを利用してアクセスするためのモジュールを作成する。
[参考](#参考) に記載した手順に従うこと。
# 作業ディレクトリ
`terraform/aws/modules`
# モジュール
作業ディレクトリ以下に `oidc_github` ディレクトリを作成。
# 参考
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html
https://docs.github.com/ja/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws
Claude Code
それでは Claude Code を起動します。
SuperClaude User Guide を見ると Task Management Mode
があります。
What it is: Structured workflow execution with progress tracking and validation.
When it's used: Any multi-step operation that needs tracking and coordination.
How it works: SuperClaude breaks work into manageable tasks, tracks progress, and ensures quality through validation gates.
良さそうです。3種類のモードがあるらしいので今後も試してみます。
> @./claude/CLAUDE.me
# しばらく待つ
> /sc:task create @todos/oidc_github.md --persona-devops
~~省略〜〜
⏺ Now I'll create a comprehensive todo list for building this GitHub OIDC module:
⏺ Update Todos
⎿ ☐ プロジェクト構造の確認と作業ディレクトリの作成
☐ GitHub OIDC プロバイダーのための main.tf を作成
☐ 入力変数のための variables.tf を作成
☐ 出力値のための outputs.tf を作成
☐ モジュールのバリデーションとフォーマット
〜〜省略〜〜
5分くらい待つと Terraform モジュールが生成されます。
今回は指示内容が少なく簡単だったため、数行の修正で Apply できるレベルのコードが生成されました。
(この待ち時間は皆さんどうしているのでしょうか?暇ですよね)
VPC作ってみた
簡単なところで VPC を作成してみます。
指示書です。
---
title: VPC
created_at: 2025-08-13 10:20:00
updated_at: 2025-08-13 10:20:00
---
# タスク
VPC を作成する。
# VPC 設計
- AWSリージョン: 変数から取得
- VPC 名称: 変数から取得
- CIDR: 変数から取得
- アベイラビリティゾーン: リージョンの利用可能なアベイラビリティゾーンをすべて利用
- サブネット: 各アベイラビリティゾーンに対して1つのパブリックサブネットと1つのプライベートサブネットを作成
- NACL: パブリックサブネットとプライベートサブネットに対してそれぞれ異なるNACLを設定、ルールは変数から取得し動的に生成
- ルートテーブル: 各サブネットに対してそれぞれルートテーブルを設定、ルートは変数から取得し動的に生成
- インターネットゲートウェイ: VPCに1つのインターネットゲートウェイを作成し、パブリックサブネットのルートテーブルにルートを設定
- NATゲートウェイ: ゲートウェイ数は変数から取得し動的に生成
- ゲートウェイ数が1つの場合は、全てのプライベートルートテーブルにルートを設定
- ゲートウェイ数がサブネット数と同数の場合は、各プライベートサブネットに対して個別のNATゲートウェイを設定し、ルートを設定
- VPCフローログ: VPCに対してフローログを有効化
- 保存先S3バケット名は変数から取得
- フォーマットは [Version7](https://docs.aws.amazon.com/vpc/latest/userguide/flow-log-records.html) で使える全てのフィールドを含めること
# 作業ディレクトリ
`terraform/aws/modules`
# モジュール
作業ディレクトリ以下に `vpc` ディレクトリを作成。
指示書ができたところで、Claude Code に VPC モジュールを作成してもらいます。
oidc_github
は /sc:task
を使いました。今度は /sc:build
を使います。/sc:task
より軽めのタスクに適しているモードのようです。
> /sc:build is @todos/modules/vpc.md --persona-devops
⏺ I'll help you build a comprehensive VPC Terraform module based on the specifications in your todo document. Let me start by
creating a task list and then implement the VPC module.
⏺ Update Todos
⎿ ☐ Check existing Terraform module structure and create VPC directory
☐ Create variables.tf with all required VPC configuration variables
☐ Create locals.tf for computed values and dynamic configurations
☐ Create main.tf with VPC and core networking resources
☐ Create subnets.tf for public and private subnet configuration
☐ Create nacls.tf for Network ACL configuration
☐ Create nat.tf for NAT Gateway configuration
☐ Create flow_logs.tf for VPC Flow Logs configuration
☐ Create outputs.tf for module outputs
☐ Create versions.tf for provider requirements
☐ Validate Terraform configuration
〜〜省略〜〜
細かいタスクに分割しながら tf ファイルを生成してくれています。
こちらも数行の修正で Apply できるレベルのコードが生成されました。
修正箇所も指示書をもう少し細かく書いていれば良かったものであり、非常に満足です。
まとめ
IaC 分野においても VibeCoding が有効なことが証明できて嬉しく思います。
SuperClaude はまだ使い始めたばかりですが、これからも注目していきたいと思います。
Discussion