mcpField
T
terraform-generator

terraform-generator

github.com/akin-ozerクラウド・DevOps329644 回インストール16 週間前に更新
リポジトリ

terraform-generator について

terraform-generatorは、ベストプラクティスに沿ってTerraform設定を生成するスキルで、インフラ設定作業を対象とします。独自Providerやモジュールの文書確認、動的データソースと重要リソースの保護、検証と修正を求めます。

主な機能

  1. 01要件に沿ったTerraform設定の生成
  2. 02独自Providerとモジュールの文書確認
  3. 03参照パターンとセキュリティ慣行の適用
  4. 04動的データソースとライフサイクル保護の追加
  5. 05設定を検証し失敗項目を修正

活用シーン

  1. 01インフラリソース用Terraformの作成
  2. 02サードパーティProviderやモジュールの使い方確認
  3. 03設定の構文とセキュリティ上の問題確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/akin-ozer/cc-devops-skills --skill terraform-generator

インストール後、Claude Code で/terraform-generatorを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

assets/
README.md
assets/minimal-project/
main.tf
outputs.tf
README.md
terraform.tfvars.example
variables.tf
versions.tf
references/
common_patterns.md
provider_examples.md
terraform_best_practices.md
scripts/
check_feature_version_consistency.sh
run_ci_checks.sh
tests/
test_feature_version_consistency.sh

詳細

Terraform ジェネレーター

概要

このスキルを使うと、ベストプラクティスと最新の標準に従った、本番環境で使用できる Terraform 構成を生成できます。カスタムプロバイダーやモジュールの検証とドキュメント検索も自動的に統合されます。

重要な要件のチェックリスト

停止してください:すべての手順を順番に完了する必要があります。必須の手順を省略しないでください。

手順アクション必須
1要件を把握する(プロバイダー、リソース、モジュール)✅ 必須
2カスタムプロバイダー/モジュールを確認し、ドキュメントを検索する✅ 必須
3生成の前にリファレンスファイルを参照する✅ 必須
4すべてのベストプラクティスに従って Terraform ファイルを生成する✅ 必須
5動的な値(リージョン、アカウント、AMI)にはデータソースを含める✅ 必須
6重要なリソース(KMS、データベース)にライフサイクルルールを追加する✅ 必須
7Skill(devops-skills:terraform-validator) を呼び出す✅ 必須
8すべての検証/セキュリティ上の失敗を修正し、再検証する✅ 必須
9使用方法(ファイル、次の手順、セキュリティ)を説明する✅ 必須

重要: 検証(terraform validate またはセキュリティスキャン)が失敗した場合は、問題を修正し、すべてのチェックに合格するまで検証を再実行する必要があります。チェックに失敗したまま手順 9 に進まないでください。

基本的なワークフロー

Terraform 構成を生成するときは、次のワークフローに従ってください。

手順 1:要件を把握する

ユーザーのリクエストを分析し、次の点を判断します。

  • 作成する必要があるインフラストラクチャリソース
  • 必要な Terraform プロバイダー(AWS、Azure、GCP、カスタムなど)
  • 使用するモジュールがあるかどうか(公式、コミュニティ、カスタム)
  • プロバイダーとモジュールのバージョン制約
  • 必要な変数入力と出力
  • 状態のバックエンド構成(ローカル、S3、リモートなど)
手順 2:カスタムプロバイダー/モジュールを確認する

構成を生成する前に、カスタムまたはサードパーティのプロバイダー/モジュールが関係するかどうかを確認します。

標準プロバイダー(検索不要):

  • hashicorp/aws
  • hashicorp/azurerm
  • hashicorp/google
  • hashicorp/kubernetes
  • その他の公式 HashiCorp プロバイダー

カスタム/サードパーティのプロバイダー/モジュール(ドキュメント検索が必要):

  • サードパーティのプロバイダー(例:datadog/datadog、mongodb/mongodbatlas)
  • Terraform Registry のカスタムモジュール
  • プライベートまたは会社固有のモジュール
  • コミュニティモジュール

カスタムプロバイダー/モジュールが検出された場合:

  1. WebSearch を使って、バージョン固有のドキュメントを検索します。

    Search query format: "[provider/module name] terraform [version] documentation [specific resource]"
    Example: "datadog terraform provider v3.30 monitor resource documentation"
    Example: "terraform-aws-modules vpc version 5.0 documentation"
    
  2. 次の内容を中心に検索します。

    • 公式ドキュメント(registry.terraform.io、プロバイダーのウェブサイト)
    • 必須および任意の引数
    • 属性の参照
    • 使用例
    • バージョン互換性に関する注意事項
  3. Context7 MCP が利用可能で、プロバイダー/モジュールがサポートされている場合は、代替手段として使用します。

    mcp__context7__resolve-library-id → mcp__context7__query-docs
    
手順 2.5:リファレンスファイルを参照する(必須)

構成を生成する前に、次の対応表に従ってリファレンスファイルを必ず参照してください。

リファレンス要件読むタイミング
terraform_best_practices.md必須常に。基本となる必須パターンが含まれています
provider_examples.md必須AWS、Azure、GCP、または Kubernetes のリソースを生成する場合
common_patterns.md既定では任意。複雑なリクエストでは必須マルチ環境、ワークスペース、構成、DR、または条件付きのパターンを扱う場合

パスを指定してリファレンスを開きます。

devops-skills-plugin/skills/terraform-generator/references/terraform_best_practices.md
devops-skills-plugin/skills/terraform-generator/references/provider_examples.md
devops-skills-plugin/skills/terraform-generator/references/common_patterns.md
ステップ 3:Terraform 設定の生成

ベストプラクティスに従って HCL ファイルを生成します。

ファイル構成:

terraform-project/
├── main.tf           # Primary resource definitions
├── variables.tf      # Input variable declarations
├── outputs.tf        # Output value declarations
├── versions.tf       # Provider version constraints
├── terraform.tfvars  # Variable values (optional, for examples)
└── backend.tf        # Backend configuration (optional)

従うべきベストプラクティス:

  1. プロバイダーの設定:

    terraform {
      required_version = ">= 1.10, < 2.0"
    
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 6.0"  # Major pin; verify exact current version when needed
        }
      }
    }
    
    provider "aws" {
      region = var.aws_region
    }
    
  2. リソースの命名:

    • 内容が明確にわかるリソース名を使用します
    • snake_case の規則に従います
    • 有用な場合は、名前にリソースタイプを含めます
    resource "aws_instance" "web_server" {
      # ...
    }
    
  3. 変数の宣言:

    variable "instance_type" {
      description = "EC2 instance type for web servers"
      type        = string
      default     = "t3.micro"
    
      validation {
        condition     = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type)
        error_message = "Instance type must be t3.micro, t3.small, or t3.medium."
      }
    }
    
  4. 出力値:

    output "instance_public_ip" {
      description = "Public IP address of the web server"
      value       = aws_instance.web_server.public_ip
    }
    
  5. 参照にはデータソースを使用:

    data "aws_ami" "ubuntu" {
      most_recent = true
      owners      = ["099720109477"] # Canonical
    
      filter {
        name   = "name"
        values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
      }
    }
    
  6. モジュールの使用:

    module "vpc" {
      source  = "terraform-aws-modules/vpc/aws"
      version = "5.0.0"
    
      name = "my-vpc"
      cidr = "10.0.0.0/16"
    
      azs             = ["us-east-1a", "us-east-1b"]
      private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
      public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]
    }
    
  7. 計算値には locals を使用:

    locals {
      common_tags = {
        Environment = var.environment
        ManagedBy   = "Terraform"
        Project     = var.project_name
      }
    }
    
  8. 必要に応じてライフサイクルルールを設定:

    resource "aws_instance" "example" {
      # ...
    
      lifecycle {
        create_before_destroy = true
        prevent_destroy       = true
        ignore_changes        = [tags]
      }
    }
    
  9. 繰り返しの設定には動的ブロックを使用:

    resource "aws_security_group" "example" {
      # ...
    
      dynamic "ingress" {
        for_each = var.ingress_rules
        content {
          from_port   = ingress.value.from_port
          to_port     = ingress.value.to_port
          protocol    = ingress.value.protocol
          cidr_blocks = ingress.value.cidr_blocks
        }
      }
    }
    
  10. コメントとドキュメント:

    • 複雑なロジックを説明するコメントを追加します
    • 特定の値を使用する理由を記載します
    • 変数の説明に例を含めます

セキュリティのベストプラクティス:

  • 機密情報をハードコードしないでください(変数を使用します)
  • AMI やその他の動的な値にはデータソースを使用します
  • 最小権限の IAM ポリシーを実装します
  • デフォルトで暗号化を有効にします
  • 安全なバックエンド設定を使用します
必須:動的な値に対するデータソース(プロバイダーに応じた設定)

動的なインフラストラクチャの値を取得するために、プロバイダーに適したデータ参照を必ず含めてください。クラウド、アカウント、リージョン、イメージの ID をハードコードしないでください。

プロバイダー必須の動的コンテキスト一般的なデータソース
AWSリージョン/アカウント/AZ/イメージ IDaws_region、aws_caller_identity、aws_availability_zones、aws_ami
Azureテナント/サブスクリプション/クライアントのコンテキストazurerm_client_config、azurerm_subscription
GCPプロジェクト/クライアントのコンテキスト/ゾーンの検出google_client_config、google_compute_zones、google_compute_image
Kubernetes信頼できるソースから取得するクラスターのエンドポイント/認証情報モジュールの出力またはクラウドのデータソースを使用し、トークンやエンドポイントのハードコードは避けます
# AWS dynamic context
data "aws_region" "current" {}
data "aws_caller_identity" "current" {}

# Azure dynamic context
data "azurerm_client_config" "current" {}
data "azurerm_subscription" "current" {}

# GCP dynamic context
data "google_client_config" "current" {}
必須:ライフサイクルと削除に対する保護(プロバイダーに応じた設定)

ステートフルなリソースや重要なリソースを誤って破棄/削除しないよう、Terraform のライフサイクルとプロバイダー固有の保護機能の両方を使用して保護してください。

プロバイダー重要なリソースの種類必須の保護メカニズム
AWSKMS、RDS、S3 データバケット、DynamoDB、ElastiCache、シークレットlifecycle { prevent_destroy = true } と、対応している場合はサービス固有の削除保護
AzureKey Vault、SQL、Storage、ステートフルなコンピューティングリソース適切な場合は prevent_destroy を設定し、プロバイダーの機能フラグ/リソース削除保護も使用
GCPCloud SQL、GKE、ストレージ、ステートフルなコンピューティングリソースprevent_destroy と、対応している場合はリソースレベルの deletion_protection = true
Kubernetesステートフルなワークロードと永続データ破壊的な置換パターンを避け、基盤となるクラウドリソースを保護します
resource "aws_db_instance" "main" {
  # ...
  deletion_protection = true
  lifecycle {
    prevent_destroy = true
  }
}

resource "google_sql_database_instance" "main" {
  # ...
  deletion_protection = true
}
必須:オブジェクトストレージのライフサイクル保護

AWS S3 のライフサイクル設定を使用する場合、未完了のマルチパートアップロードを中止するルールを必ず含めてください。

resource "aws_s3_bucket_lifecycle_configuration" "main" {
  bucket = aws_s3_bucket.main.id

  # REQUIRED: Abort incomplete multipart uploads to prevent storage costs
  rule {
    id     = "abort-incomplete-uploads"
    status = "Enabled"

    # Filter applies to all objects (empty filter = all objects)
    filter {}

    abort_incomplete_multipart_upload {
      days_after_initiation = 7
    }
  }

  # Other lifecycle rules (e.g., transition to IA)
  rule {
    id     = "transition-to-ia"
    status = "Enabled"

    filter {
      prefix = ""  # Apply to all objects
    }

    transition {
      days          = 90
      storage_class = "STANDARD_IA"
    }

    noncurrent_version_transition {
      noncurrent_days = 30
      storage_class   = "STANDARD_IA"
    }

    noncurrent_version_expiration {
      noncurrent_days = 365
    }
  }
}

理由: 未完了のマルチパートアップロードはストレージを消費し、コストが発生します。Checkov のチェック CKV_AWS_300 は AWS でこの設定を必須とします。

Azure/GCP のオブジェクトストレージでは、古いオブジェクトや旧バージョンに対して同等のライフサイクル/保持ルールを追加してください。

ステップ 4:生成した設定を検証する(必須)

Terraform ファイルを生成した後は、必ず devops-skills:terraform-validator スキルを使用して検証してください。

Invoke: Skill(devops-skills:terraform-validator)

devops-skills:terraform-validator スキルでは、次の処理が行われます。

  1. terraform fmt -check で HCL 構文を確認します
  2. terraform init で設定を初期化します
  3. terraform validate で設定を検証します
  4. Checkov でセキュリティスキャンを実行します
  5. (依頼された場合)terraform plan でドライランテストを実行します

重要:修正と再検証のループ

検証またはセキュリティチェックが1つでも失敗した場合は、必ず次の対応を行ってください。

  1. エラーを確認する - 何が、なぜ失敗したのかを把握します
  2. 問題を修正する - 生成したファイルを編集して問題を解決します
  3. 検証を再実行する - Skill(devops-skills:terraform-validator) を再度呼び出します
  4. すべてのチェックに合格するまで繰り返す - チェックが失敗したまま先に進んではいけません
┌─────────────────────────────────────────────────────────┐
│  VALIDATION FAILED?                                      │
│                                                          │
│  ┌─────────┐    ┌─────────┐    ┌─────────────────────┐  │
│  │  Fix    │───▶│ Re-run  │───▶│ All checks pass?    │  │
│  │  Issue  │    │ Skill   │    │ YES → Step 5        │  │
│  └─────────┘    └─────────┘    │ NO  → Loop back     │  │
│       ▲                         └─────────────────────┘  │
│       │                                    │             │
│       └────────────────────────────────────┘             │
└─────────────────────────────────────────────────────────┘

修正が必要な一般的な検証エラー:

チェック問題修正方法
CKV_AWS_300マルチパートアップロードの中断設定がないabort_incomplete_multipart_upload ルールを追加します
CKV_AWS_24SSH が 0.0.0.0/0 に対して開放されている特定の CIDR に制限します
CKV_AWS_16RDS の暗号化が無効になっているstorage_encrypted = true を追加します
terraform validateリソースの引数が無効プロバイダーのドキュメントを確認します

検証中にカスタムプロバイダーが検出された場合:

  • devops-skills:terraform-validator スキルがドキュメントを自動的に取得します
  • 取得したドキュメントを使用して問題を修正します
ステップ 5:使用方法を提示する(必須)

すべてのチェックに合格し、生成と検証が正常に完了した後、必ず次の内容をユーザーに提示してください。

必須の出力形式:

## Generated Files

| File | Description |
|------|-------------|
| `<actual-file-path>` | What was generated in that file |

Only list files that were actually generated for this request. Do not include placeholder paths or files that do not exist.

## Next Steps

1. Review and customize `terraform.tfvars` with your values
2. Initialize Terraform:
   ```bash
   terraform init
  1. 実行計画を確認します。
    terraform plan
    
  2. 設定を適用します。
    terraform apply
    

カスタマイズに関する注意事項

  • terraform.tfvars の variable_name を更新します
  • リモートステート用に backend.tf でバックエンドを設定します
  • 必要に応じてリソース名やタグを調整します

セキュリティに関する注意事項

⚠️ 適用する前に:

  • IAM ポリシーと権限を確認します
  • 機密情報をバージョン管理にコミットしないようにします
  • 暗号化を有効にしたステートバックエンドを設定します
  • チームでの共同作業用にステートロックを設定します

> **IMPORTANT:** Do NOT skip Step 5. The user needs actionable guidance on how to use the generated configuration.

## Common Generation Patterns

### Pattern 1: Simple Resource Creation

User request: "Create an AWS S3 bucket with versioning"

Generated files:
- `main.tf` - S3 bucket resource with versioning enabled
- `variables.tf` - Bucket name, tags variables
- `outputs.tf` - Bucket ARN and name outputs
- `versions.tf` - AWS provider version constraints

### Pattern 2: Module-Based Infrastructure

User request: "Set up a VPC using the official AWS VPC module"

Actions:
1. Identify module: terraform-aws-modules/vpc/aws
2. Web search for latest version and documentation
3. Generate configuration using module with appropriate inputs
4. Validate with devops-skills:terraform-validator

### Pattern 3: Multi-Provider Configuration

User request: "Create infrastructure across AWS and Datadog"

Actions:
1. Identify standard provider (AWS) and custom provider (Datadog)
2. Web search for Datadog provider documentation with version
3. Generate configuration with both providers properly configured
4. Ensure provider aliases if needed
5. Validate with devops-skills:terraform-validator

### Pattern 4: Complex Resource with Dependencies

User request: "Create an ECS cluster with ALB and auto-scaling"

Generated structure:
- Multiple resource blocks with proper dependencies
- Data sources for AMIs, availability zones, etc.
- Local values for computed configurations
- Comprehensive variables and outputs
- Proper dependency management using implicit references

## Error Handling

**Common Issues and Solutions:**

1. **Provider Not Found:**
   - Ensure provider is listed in `required_providers` block
   - Verify source address format: `namespace/name`
   - Check version constraint syntax

2. **Invalid Resource Arguments:**
   - Refer to web search results for custom providers
   - Check for required vs optional arguments
   - Verify attribute value types (string, number, bool, list, map)

3. **Circular Dependencies:**
   - Review resource references
   - Use `depends_on` explicit dependencies if needed
   - Consider breaking into separate modules

4. **Validation Failures:**
   - Run devops-skills:terraform-validator skill to get detailed errors
   - Fix issues one at a time
   - Re-validate after each fix

## Version Awareness

Always consider version compatibility:

1. **Terraform Version:**
   - Use `required_version` constraint with both lower and upper bounds
   - If generated configuration includes write-only arguments (`*_wo`): use `required_version = ">= 1.11, < 2.0"`.
   - Else if it uses ephemeral constructs (`ephemeral` blocks, ephemeral variables/outputs) without write-only arguments: use `required_version = ">= 1.10, < 2.0"`.
   - Else use the project baseline (default `>= 1.8, < 2.0` unless repository policy requires newer).
   - Use `>= 1.14, < 2.0` for latest features (actions, query command)
   - Document any version-specific features used (see below)

2. **Provider Version Policy (canonical):**
   - Pin provider major versions with `~>` constraints (for example `~> 6.0`, `~> 4.0`, `~> 7.0`).
   - Do not claim "latest" version unless verified online during the current run.
   - Keep cross-provider guidance consistent:
     - AWS family: major-pin policy (for example `~> 6.0`)
     - AzureRM: major-pin policy (for example `~> 4.0`)
     - Google: major-pin policy (for example `~> 7.0`)
     - Kubernetes: major/minor pin based on target cluster/provider compatibility
   - Use the same provider/version language in `SKILL.md`, `references/terraform_best_practices.md`, and template `assets/minimal-project/versions.tf`.

3. **Module Versions:**
   - Always pin module versions
   - Review module documentation for version compatibility
   - Test module updates in non-production first

### Required Version Decision Table

| Generated Output Contains | Required Version to Emit |
|---------------------------|--------------------------|
| Any write-only argument (`*_wo`) | `>= 1.11, < 2.0` |
| Ephemeral constructs only (no write-only) | `>= 1.10, < 2.0` |
| Neither write-only nor ephemeral | Project baseline (default `>= 1.8, < 2.0`) |

#### Feature-Gating Examples

```hcl
# Positive: write-only usage requires Terraform 1.11+
terraform {
  required_version = ">= 1.11, < 2.0"
}

ephemeral "random_password" "db_password" {
  length = 16
}

resource "aws_db_instance" "main" {
  identifier          = "mydb"
  instance_class      = "db.t3.micro"
  allocated_storage   = 20
  engine              = "postgres"
  username            = "admin"
  skip_final_snapshot = true

  password_wo         = ephemeral.random_password.db_password.result
  password_wo_version = 1
}
# Negative: reject this pattern (write-only with Terraform 1.10)
terraform {
  required_version = ">= 1.10, < 2.0"
}

resource "aws_db_instance" "invalid" {
  password_wo = "do-not-generate-this"
}
Terraform バージョン別機能マトリックス
機能最小バージョン
terraform_data リソース1.4+
import {} ブロック1.5+
check {} ブロック1.5+
ネイティブテスト(.tftest.hcl)1.6+
テストのモック1.7+
removed {} ブロック1.7+
プロバイダー定義関数1.8+
型をまたぐリファクタリング1.8+
拡張された変数の検証1.9+
templatestring 関数1.9+
エフェメラルリソース1.10+
書き込み専用引数1.11+
S3 ネイティブステートロック1.11+
for_each を使用するインポートブロック1.12+
アクションブロック1.14+
リストリソース(tfquery.hcl)1.14+
terraform query コマンド1.14+

Terraform の最新機能(1.8+)

プロバイダー定義関数(Terraform 1.8+)

プロバイダー定義関数を使用すると、Terraform の組み込み関数をプロバイダー固有のロジックで拡張できます。

構文: provider::<provider_name>::<function_name>(arguments)

# AWS Provider Functions (v5.40+)
locals {
  # Parse an ARN into components
  parsed_arn = provider::aws::arn_parse(aws_instance.web.arn)
  account_id = local.parsed_arn.account
  region     = local.parsed_arn.region

  # Build an ARN from components
  custom_arn = provider::aws::arn_build({
    partition = "aws"
    service   = "s3"
    region    = ""
    account   = ""
    resource  = "my-bucket/my-key"
  })
}

# Google Cloud Provider Functions (v5.23+)
locals {
  # Extract region from zone
  region = provider::google::region_from_zone(var.zone)  # "us-west1-a" → "us-west1"
}

# Kubernetes Provider Functions (v2.28+)
locals {
  # Encode HCL to Kubernetes manifest YAML
  manifest_yaml = provider::kubernetes::manifest_encode(local.deployment_config)
}
エフェメラルリソース(Terraform 1.10+)

エフェメラルリソースは、ステートファイルやプランファイルに一切保存されない一時的な値を提供します。シークレットを安全に扱うために不可欠です。

# Generate a password that never touches state
ephemeral "random_password" "db_password" {
  length           = 16
  special          = true
  override_special = "!#$%&*()-_=+[]{}<>:?"
}

# Fetch secrets ephemerally from AWS Secrets Manager
ephemeral "aws_secretsmanager_secret_version" "api_key" {
  secret_id = aws_secretsmanager_secret.api_key.id
}

# Ephemeral variables (declare with ephemeral = true)
variable "temporary_token" {
  type      = string
  ephemeral = true  # Value won't be stored in state
}

# Ephemeral outputs
output "session_token" {
  value     = ephemeral.aws_secretsmanager_secret_version.api_key.secret_string
  ephemeral = true  # Won't be stored in state
}
書き込み専用引数(Terraform 1.11+)

書き込み専用引数はエフェメラル値を受け取り、保存されることはありません。_wo サフィックスを使用し、バージョン属性が必要です。

terraform {
  required_version = ">= 1.11, < 2.0"
}

# Secure database password handling
ephemeral "random_password" "db_password" {
  length = 16
}

resource "aws_db_instance" "main" {
  identifier        = "mydb"
  instance_class    = "db.t3.micro"
  allocated_storage = 20
  engine            = "postgres"
  username          = "admin"

  # Write-only password - never stored in state!
  password_wo         = ephemeral.random_password.db_password.result
  password_wo_version = 1  # Increment to trigger password rotation

  skip_final_snapshot = true
}

# Secrets Manager with write-only
resource "aws_secretsmanager_secret_version" "db_password" {
  secret_id = aws_secretsmanager_secret.db_password.id

  # Write-only secret string
  secret_string_wo         = ephemeral.random_password.db_password.result
  secret_string_wo_version = 1
}
拡張された変数の検証(Terraform 1.9+)

検証条件から、ほかの変数、データソース、ローカル値を参照できるようになりました。

# Reference data sources in validation
data "aws_ec2_instance_type_offerings" "available" {
  filter {
    name   = "location"
    values = [var.availability_zone]
  }
}

variable "instance_type" {
  type        = string
  description = "EC2 instance type"

  validation {
    # NEW: Can reference data sources
    condition = contains(
      data.aws_ec2_instance_type_offerings.available.instance_types,
      var.instance_type
    )
    error_message = "Instance type ${var.instance_type} is not available in the selected AZ."
  }
}

# Cross-variable validation
variable "min_instances" {
  type    = number
  default = 1
}

variable "max_instances" {
  type    = number
  default = 10

  validation {
    # NEW: Can reference other variables
    condition     = var.max_instances >= var.min_instances
    error_message = "max_instances must be >= min_instances"
  }
}
S3 ネイティブステートロック(Terraform 1.11+)

S3 は DynamoDB を使用しないネイティブステートロックに対応しました。

terraform {
  backend "s3" {
    bucket       = "my-terraform-state"
    key          = "project/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true

    # NEW: S3-native locking (Terraform 1.11+)
    use_lockfile = true

    # DEPRECATED: DynamoDB locking (still works but no longer required)
    # dynamodb_table = "terraform-locks"
  }
}
インポートブロック(Terraform 1.5+)

コマンドライン操作を使わずに、宣言的にリソースをインポートできます。

# Import existing resources declaratively
import {
  to = aws_instance.web
  id = "i-1234567890abcdef0"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  # ... configuration must match existing resource
}

# Import with for_each
import {
  for_each = var.existing_bucket_names
  to       = aws_s3_bucket.imported[each.key]
  id       = each.value
}
Moved ブロックと Removed ブロック

リソースを破棄せずに安全にリファクタリングできます。

# Rename a resource
moved {
  from = aws_instance.old_name
  to   = aws_instance.new_name
}

# Move to a module
moved {
  from = aws_vpc.main
  to   = module.networking.aws_vpc.main
}

# Cross-type refactoring (1.8+)
moved {
  from = null_resource.example
  to   = terraform_data.example
}

# Remove resource from state without destroying (1.7+)
removed {
  from = aws_instance.legacy

  lifecycle {
    destroy = false  # Keep the actual resource, just remove from state
  }
}
for_each を使用したインポートブロック(Terraform 1.12+)

for_each メタ引数を使用して、複数のリソースをインポートします。

# Import multiple S3 buckets using a map
locals {
  buckets = {
    "staging" = "bucket1"
    "uat"     = "bucket2"
    "prod"    = "bucket3"
  }
}

import {
  for_each = local.buckets
  to       = aws_s3_bucket.this[each.key]
  id       = each.value
}

resource "aws_s3_bucket" "this" {
  for_each = local.buckets
}

# Import across module instances using list of objects
locals {
  module_buckets = [
    { group = "one", key = "bucket1", id = "one_1" },
    { group = "one", key = "bucket2", id = "one_2" },
    { group = "two", key = "bucket1", id = "two_1" },
  ]
}

import {
  for_each = local.module_buckets
  id       = each.value.id
  to       = module.group[each.value.group].aws_s3_bucket.this[each.value.key]
}
Actions ブロック(Terraform 1.14+)

Actions を使用すると、標準の CRUD モデル以外のプロバイダー定義の操作を実行できます。Lambda の呼び出し、キャッシュの無効化、データベースのバックアップなどの操作に使用します。

# Invoke a Lambda function (example syntax)
action "aws_lambda_invoke" "process_data" {
  function_name = aws_lambda_function.processor.function_name
  payload       = jsonencode({ action = "process" })
}

# Create CloudFront invalidation
action "aws_cloudfront_create_invalidation" "invalidate_cache" {
  distribution_id = aws_cloudfront_distribution.main.id
  paths           = ["/*"]
}

# Actions support for_each
action "aws_lambda_invoke" "batch_process" {
  for_each = toset(["task1", "task2", "task3"])

  function_name = aws_lambda_function.processor.function_name
  payload       = jsonencode({ task = each.value })
}

ライフサイクルを介したアクションのトリガー:

リソースのライフサイクルブロック内で action_trigger を使用すると、アクションを自動的に呼び出せます。

resource "aws_lambda_function" "example" {
  function_name = "my-function"
  # ... other config ...

  lifecycle {
    action_trigger {
      events  = [after_create, after_update]
      actions = [action.aws_lambda_invoke.process_data]
    }
  }
}

action "aws_lambda_invoke" "process_data" {
  function_name = aws_lambda_function.example.function_name
  payload       = jsonencode({ action = "initialize" })
}

手動での呼び出し:

アクションは CLI から手動で呼び出すこともできます。

terraform apply -invoke action.aws_lambda_invoke.process_data
リストリソースと Query コマンド(Terraform 1.14+)

.tfquery.hcl ファイルと terraform query コマンドを使用して、既存のインフラストラクチャをクエリし、フィルタリングします。

# my-resources.tfquery.hcl
# Define list resources to query existing infrastructure

list "aws_instance" "web_servers" {
  filter {
    name   = "tag:Environment"
    values = [var.environment]
  }

  include_resource = true  # Include full resource details
}

list "aws_s3_bucket" "data_buckets" {
  filter {
    name   = "tag:Purpose"
    values = ["data-storage"]
  }
}
# Query infrastructure and output results
terraform query

# Generate import configuration from query results
terraform query -generate-config-out="import_config.tf"

# Output in JSON format
terraform query -json

# Use with variables
terraform query -var 'environment=prod'
事前条件と事後条件(Terraform 1.5+)

リソースのライフサイクル内にカスタム検証を追加します。

resource "aws_instance" "example" {
  instance_type = "t3.micro"
  ami           = data.aws_ami.example.id

  lifecycle {
    # Check before creation
    precondition {
      condition     = data.aws_ami.example.architecture == "x86_64"
      error_message = "The selected AMI must be for the x86_64 architecture."
    }

    # Verify after creation
    postcondition {
      condition     = self.public_dns != ""
      error_message = "EC2 instance must be in a VPC that has public DNS hostnames enabled."
    }
  }
}

# Preconditions on outputs
output "web_url" {
  value = "https://${aws_instance.web.public_dns}"

  precondition {
    condition     = aws_instance.web.public_dns != ""
    error_message = "Instance must have a public DNS name."
  }
}

リソース

references/

references/ ディレクトリには、参照用の詳細なドキュメントが含まれています。

  • terraform_best_practices.md - 包括的なベストプラクティスガイド
  • common_patterns.md - Terraform の一般的なパターンと例
  • provider_examples.md - 人気のあるプロバイダー向けの設定例

相対パスを指定して、参照先を直接開きます。

devops-skills-plugin/skills/terraform-generator/references/[filename].md
assets/

assets/ ディレクトリにはテンプレートファイルが含まれています。

  • minimal-project/ - 最小限の Terraform プロジェクトテンプレート

テンプレートは、ユーザー固有のニーズに合わせてコピーし、カスタマイズできます。

注意事項

  • 生成後は必ず devops-skills:terraform-validator を実行します
  • CI で機能やバージョンの差異を確認するには、bash scripts/run_ci_checks.sh を実行します
  • カスタムプロバイダーやモジュールには、ウェブ検索が不可欠です
  • 設定では、最小驚きの原則に従います
  • 設定を読みやすく、保守しやすいものにします
  • 役立つコメントとドキュメントを含めます
  • 必要に応じて、terraform.tfvars に現実的な例を生成します

コメント