目次

Amazon CodeGuru Reviewer 完全ガイド v2.0(2026年最新対応)

ML自動コードレビュー・開発チーム統合・End-of-Life対応


目次


ドキュメントメタデータ

  • 最終更新: 2026-04-26
  • バージョン: v2.0
  • 対象者: Java/Python 開発チーム、コードレビューアー、DevOps エンジニア
  • 難易度: 中級
  • ⚠️ 重要: End-of-Life 2025-04-30(CodeGuru Security / Q Developer への移行推奨)
  • 関連サービス: CodeGuru Security、Amazon Q、CodePipeline、GitHub、GitLab、Bitbucket

概要と課題

本質

Amazon CodeGuru Reviewer「機械学習と静的解析(SAST)を組み合わせた Java・Python コードの自動コードレビューサービス」 である。GitHub・GitLab・Bitbucket・AWS CodeCommit の Pull Request に直接コメントを投稿し、セキュリティ脆弱性・リソースリーク・AWS SDK のベストプラクティス違反・パフォーマンス問題を自動検出する。

⚠️ 重要: 2025-04-30 の End-of-Life に伴い、セキュリティ検出機能は Amazon CodeGuru Security・Q Developer に統合される。新規採用では CodeGuru Security を優先推奨。

このサービスを選ぶ理由

なぜ Amazon CodeGuru Reviewer なのか?

  1. PR マージ前の自動品質ゲート

    • 開発者が main・release ブランチへ PR を作成
    • CodeGuru が自動解析 → PR に行番号付きコメント投稿
    • ヒューマンレビューで見落としやすいバグパターン(メモリリーク・null チェック漏れ)を機械学習で検出
    • CRITICAL・HIGH のみブロック・マージ前修正要求が可能
  2. AWS SDK 固有のベストプラクティス検出

    • SonarQube・ESLint などの汎用ツールでは検出困難な AWS 固有の問題を検出
    • 例: SQS メッセージ削除漏れ・DynamoDB 強整合性読み取り過剰・Lambda タイムアウト設定漏れ
    • AWS SDK の API 呼び出しパターンを学習したモデルだから実現可能
  3. Secrets Detection(認証情報ハードコーディング検出)が無料

    • AWS Access Key・API Key・OAuth Token・SSH 秘密鍵などを自動検出
    • 他の SAST ツールと異なり、無料枠でこの機能を使用可能
    • ソースコードへの認証情報混入を本番前にブロック
  4. PR コメント統合で開発フローを分断しない

    • 結果を別ツールで確認する必要なし
    • GitHub・Bitbucket のネイティブ PR コメントとして投稿
    • Approve/Request Changes 判断に組み込み可能
  5. Java・Python 専門の深い解析

    • コンパイル言語(Java)・インタプリタ言語(Python)の特性に合わせた検出ルール
    • 言語別に 50+ のディテクターを搭載
    • バイトコード解析・AST(抽象構文木)ベース

このサービスを選ばない理由

  • TypeScript・Go・Rust・C# が必須 → CodeGuru Security を検討
  • セキュリティに特化したいニーズ → CodeGuru Security / Snyk Code が最適
  • IDE リアルタイムレビューが必須 → CodeGuru Security(VS Code・JetBrains プラグイン)
  • End-of-Life(2025-04-30)への対応 → CodeGuru Security への移行開始推奨

アーキテクチャと設計原則

全体構成図(Mermaid 1)

graph TB
    subgraph Developer["開発者"]
        GIT["Git Push / PR作成<br/>(GitHub/GitLab/BB)"]
    end
    
    subgraph Reviewer["CodeGuru Reviewer"]
        ASSOC["Repository Association"]
        ANALYSIS["ML Code Analysis<br/>+ SAST Detectors"]
        SECRET["Secrets Detector<br/>(無料)"]
    end
    
    subgraph Integration["統合ポイント"]
        GITHUB_PR["GitHub PR<br/>コメント投稿"]
        PIPELINE["CodePipeline<br/>Quality Gate"]
        CLOUDWATCH["CloudWatch<br/>Metrics"]
    end
    
    subgraph Result["検出結果"]
        RECOMMENDATION["Recommendation<br/>(CRITICAL/HIGH/...)"]
        FEEDBACK["Developer Feedback<br/>(対応/無視)"]
    end
    
    GIT -->|Webhook| ASSOC
    ASSOC -->|自動トリガー| ANALYSIS
    ANALYSIS -->|並行実行| SECRET
    ANALYSIS -->|行番号付き| RECOMMENDATION
    SECRET -->|ハードコード検出| RECOMMENDATION
    
    RECOMMENDATION -->|PR コメント| GITHUB_PR
    RECOMMENDATION -->|Lambda Gate| PIPELINE
    RECOMMENDATION -->|メトリクス| CLOUDWATCH
    
    GITHUB_PR -->|Review Comments| FEEDBACK
    PIPELINE -->|合格/不合格| FEEDBACK
    
    style ASSOC fill:#e8f4f8
    style ANALYSIS fill:#fff3cd
    style SECRET fill:#d4edda
    style RECOMMENDATION fill:#f8d7da

ユースケース別アーキテクチャ

┌─ Pull Request Review(最も一般的)
│  ├─ Developer: GitHub PR 作成
│  ├─ CodeGuru: Webhook で自動検出
│  └─ Feedback: PR コメントで結果通知
│
├─ CI/CD Pipeline Integration
│  ├─ CodePipeline: Build ステージ完了後
│  ├─ Lambda Gate: CodeGuru 結果を取得
│  └─ Go/NoGo: CRITICAL/HIGH で失敗判定
│
├─ On-Demand Analysis(定期スキャン)
│  ├─ AWS Console / CLI: `create-code-review`
│  ├─ S3 アップロード: コードアーカイブ
│  └─ Result: Dashboard で確認
│
└─ IDE/Local(将来対応予定)
   └─ VS Code プラグイン: 現在は CodeGuru Security のみ

検出カテゴリ・ディテクター

1. Security(セキュリティ)

対象パターン

- AWS 認証情報ハードコーディング(Secrets Detector で検出)
  AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / Database Password
  
- SQL インジェクション脆弱性
  例: String sql = "SELECT * FROM users WHERE id=" + id;  // SQL インジェクションリスク
  推奨: PreparedStatement を使用
  
- 暗号化の弱点
  MD5 / SHA-1 / DES / ECB モード(非推奨)の使用
  例: MessageDigest.getInstance("MD5")  // ❌ 弱い暗号化
  推奨: SHA-256 以上
  
- 安全でない乱数生成
  java.util.Random / Math.random() での暗号化キー生成
  推奨: java.security.SecureRandom
  
- XXE(XML External Entity)攻撃脆弱性
  DocumentBuilderFactory に外部エンティティ参照が有効な場合
  
- クロスサイト リクエスト フォージェリ(CSRF)防止不足
  Spring Security CSRF トークン未設定

2. AWS Best Practices(AWS ベストプラクティス)

対象パターン

- SDK ページネーション未使用(全件取得バグ)
  AmazonS3 listObjects()(最大 1,000 件)を繰り返し呼び出さない
  推奨: listObjectsV2() with ContinuationToken
  
- AWS API 例外処理不足
  try { s3.getObject(...) } catch (SdkException e) { log.error(e); }
  推奨: AmazonServiceException で個別ハンドリング
  
- SQS メッセージ削除漏れ(重要)
  Message msg = queue.receiveMessage();
  if (process(msg.getBody())) {
    msg.delete();  // ← 削除しないと再処理される
  }
  
- DynamoDB 強整合性読み取り過剰使用
  強整合性読み取りは通常の 2 倍コスト
  推奨: 結果整合性で十分なケースでは use
  
- Lambda タイムアウト設定不足
  TimeoutInSeconds が低すぎるとコールドスタート時に失敗
  
- IAM ロール権限が全リソース許可
  Resource: "*" は非推奨・最小権限に

3. Resource Leak(リソースリーク)

対象パターン

- InputStream / FileInputStream のクローズ漏れ
  FileInputStream fis = new FileInputStream("file.txt");
  String data = fis.toString();
  // fis.close() がない → リソースリーク
  推奨: try-with-resources または finally で close()
  
- Connection / Statement のクローズ漏れ(DB)
  Connection conn = DriverManager.getConnection(...);
  ResultSet rs = conn.createStatement().executeQuery(sql);
  // conn.close() がない
  
- Network Socket のクローズ漏れ
  Socket sock = new Socket(host, port);
  sock.getOutputStream().write(data);
  // sock.close() がない
  
- Memory Leak(メモリリーク)
  static List<Object> cache = new ArrayList<>();
  public void add(Object obj) {
    cache.add(obj);  // クリア機制なし → メモリ肥大化
  }

4. Performance(パフォーマンス)

対象パターン

- 非効率なコレクション操作
  String s = "";
  for (int i = 0; i < 1000; i++) {
    s += "data";  // ← 毎回文字列全体をコピー
  }
  推奨: StringBuilder を使用
  
- ループ内での正規表現コンパイル
  for (String line : lines) {
    if (line.matches("\\d+")) {  // ← 毎回 Pattern コンパイル
      ...
    }
  }
  推奨: Pattern を事前コンパイル
  
- N+1 クエリパターン
  for (User user : users) {
    List<Post> posts = db.query("SELECT * FROM posts WHERE user_id=" + user.id);
  }
  // ← users.size() + 1 回クエリ実行
  
- 過剰なログレベル
  logger.debug() で大量データ出力 → CPU・IO 負荷

5. Code Quality(コード品質)

対象パターン

- 変数未使用・デッドコード
  int unused = 10;
  
- null ポインタ参照リスク
  String name = getName();  // null の可能性
  int len = name.length();  // NullPointerException リスク
  
- スレッドセーフティ問題
  static List<String> sharedList = new ArrayList<>();
  public void add(String item) {
    sharedList.add(item);  // ← 複数スレッド競合リスク
  }
  推奨: synchronized / ConcurrentHashMap
  
- 複数 return パス
  メソッド内に複数の return があると可読性低下・テスト困難

コアコンポーネント

1. Repository Association

定義 CodeGuru がリポジトリにアクセスするための関連付けリソース

対応リポジトリ

- GitHub / GitHub Enterprise Cloud / GitHub Enterprise Server
- GitLab
- Bitbucket Cloud
- AWS CodeCommit
- S3(コードアーカイブ)

属性

- RepositoryAssociationArn: arn:aws:codeguru-reviewer:region:account:association/name
- RepositoryName: リポジトリ名
- Owner: オーナー(GitHub org など)
- State: Validating / Associated / Failed / Associating
- AssociatedAt: 関連付け時刻
- DisassociatedAt: 削除時刻

ライフサイクル

  • Associated → CodeGuru が PR を自動解析
  • Disassociated → 新規 PR は対象外

2. Code Review リソース

定義 単一の解析実行を表す

実行タイプ

① PullRequestReview
   - GitHub/GitLab/Bitbucket PR に基づく
   - 差分(diff)のみを解析
   - 自動トリガー

② RepositoryAnalysis
   - 全リポジトリをスキャン
   - オンデマンド実行(CLI / API / Console)
   - 手動トリガー

属性

- CodeReviewArn: arn:aws:codeguru-reviewer:region:account:code-review/...
- Type: REPOSITORY_ANALYSIS / PULL_REQUEST_REVIEW
- State: Completed / Failed / Pending / Canceled
- CreatedTime: 実行時刻
- CompletionTime: 終了時刻
- MetricsDetails: 行数・検出件数など

3. Recommendations(推奨事項)

定義 検出された個々の問題

フィールド

- RecommendationId: 一意識別子
- Severity: CRITICAL / HIGH / MEDIUM / LOW / INFO
- Category: Security / AWSBestPractices / CodeQuality / Performance / ResourceLeak
- Title: "AWS credentials detected in code"
- Description: 詳細説明
- FilePath: "src/main/java/com/example/App.java"
- LineNumber: 42
- StartLine / EndLine: コード範囲
- CodeSnippet: 問題の箇所
- RecommendedFix: 修正提案コード
- SourceCodeUrl: GitHub など外部 URL

4. Detector Library

公開ディテクター一覧 https://docs.aws.amazon.com/codeguru/detector-library/index.html

注目すべきディテクター

java/aws/empty-catch-block
  → 空の catch ブロック(例外を無視)

java/aws/unvalidated-input
  → ユーザー入力検証なし

py/sql-injection
  → Python での SQL インジェクション

py/weak-cryptography
  → 弱い暗号化関数(hashlib.md5 など)

主要ユースケース

1. GitHub PR への自動コメント統合(最も一般的)

シナリオ 開発チームが GitHub で日々コード更新し、PR 作成時に CodeGuru が自動解析→コメント投稿

# Step 1: Repository Association
aws codeguru-reviewer associate-repository \
  --repository GitHub='{"Name": "myorg/myapp"}'

# Step 2: PR 作成時に自動トリガー
# Developer: GitHub で PR 作成
# CodeGuru: Webhook 受け取り → 自動解析
# Result: PR に CRITICAL/HIGH コメント投稿

# Step 3: 開発者が PR コメント確認・修正
# GitHub UI で "Review requested" 表示

メリット

  • 別ツール不要(GitHub UI で完結)
  • リアルタイムフィードバック
  • レビュアー負担削減

2. CodePipeline 品質ゲート統合

シナリオ CodePipeline の Build ステージ完了後、CodeGuru 結果を判定してマージを許可・拒否

import boto3

def lambda_handler(event, context):
    codeguru = boto3.client('codeguru-reviewer')
    codepipeline = boto3.client('codepipeline')

    job_id = event['CodePipeline.job']['id']

    # CodeReview 結果取得
    recommendations = codeguru.list_recommendations(
        CodeReviewArn='arn:aws:codeguru-reviewer:...'
    )['RecommendationSummaries']

    # CRITICAL・HIGH の件数カウント
    critical_high = [
        r for r in recommendations 
        if r['Severity'] in ['Critical', 'High']
    ]

    if len(critical_high) == 0:
        # 合格 → Merge 許可
        codepipeline.put_job_success_result(jobId=job_id)
    else:
        # 不合格 → Merge ブロック
        codepipeline.put_job_failure_result(
            jobId=job_id,
            failureDetails={
                'message': f'{len(critical_high)} critical/high issues found',
                'type': 'JobFailed'
            }
        )

3. Secrets Detection(認証情報ハードコーディング検出)

シナリオ 開発者がうっかり AWS Access Key などをソースコードに混入 → CodeGuru が自動検出・PR コメント

# ❌ 悪い例
import boto3

AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"  # ← ハードコード
AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

s3 = boto3.client(
    's3',
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)

# CodeGuru PR コメント:
# [CRITICAL] AWS credentials detected in source code.
# Use IAM roles, environment variables, or Secrets Manager instead.

推奨対策

# ✅ 正しい例
import boto3
import os

# 環境変数・IAM ロールから自動取得
s3 = boto3.client('s3')

# または Secrets Manager
import json
from botocore.exceptions import ClientError

def get_secret(secret_name):
    sm = boto3.client('secretsmanager')
    response = sm.get_secret_value(SecretId=secret_name)
    return json.loads(response['SecretString'])

4. Lambda 関数の自動レビュー

シナリオ Lambda 関数のコード変更を PR でレビュー → CodeGuru がベストプラクティス違反を検出

import json

def lambda_handler(event, context):
    # ❌ CodeGuru が検出する問題:
    # - Exception handling が generic(Exception で catch)
    # - Timeout handling なし(デフォルト 3 秒)
    # - Resource leak(Secrets Manager クライアント未 close)
    
    try:
        secrets = boto3.client('secretsmanager').get_secret_value(SecretId='mykey')
        # ← クライアント close していない
        return {
            'statusCode': 200,
            'body': json.dumps('Success')
        }
    except Exception as e:  # ← Generic exception
        return {
            'statusCode': 500,
            'body': json.dumps(str(e))
        }

5. マイクロサービス全体のスキャン(定期スキャン)

シナリオ 複数リポジトリを一括 Associate → スケジュール実行で定期的にスキャン

# 複数リポジトリ Associate
for REPO in service-auth service-api service-worker; do
  aws codeguru-reviewer associate-repository \
    --repository GitHub='{"Name": "myorg/'$REPO'"}'
done

# Lambda で定期実行(CloudWatch Events)
@scheduled_event  # every Monday 09:00 UTC
def weekly_codereviews(event, context):
    codeguru = boto3.client('codeguru-reviewer')
    
    # 全 repository associations を取得
    associations = codeguru.list_repository_associations()
    
    for assoc in associations['RepositoryAssociations']:
        codeguru.create_code_review(
            name=f"weekly-review-{assoc['RepositoryName']}",
            repositoryAssociationArn=assoc['RepositoryAssociationArn'],
            type='RepositoryAnalysis',
            config={'RepositoryHead': {'BranchName': 'main'}}
        )

6-12. (その他 6 ユースケース省略)


設定・操作の具体例

CLI 操作(5 パターン)

1. GitHub リポジトリ Associate・Status 確認

# Associate
aws codeguru-reviewer associate-repository \
  --repository GitHub='{"Name": "myorg/myapp"}' \
  --region ap-northeast-1

# Status 確認(数秒で Associated に)
aws codeguru-reviewer describe-repository-association \
  --association-arn arn:aws:codeguru-reviewer:ap-northeast-1:123456789012:association/... \
  --query 'RepositoryAssociation.[RepositoryName,State,AssociatedAt]'

# 全 Association 一覧
aws codeguru-reviewer list-repository-associations \
  --query 'RepositoryAssociations[].{Name:RepositoryName,State:State}'

2. CodeGuru 結果取得・フィルタリング

# Code Review を取得
CODE_REVIEW_ARN="arn:aws:codeguru-reviewer:ap-northeast-1:123456789012:code-review/..."

# Recommendations 一覧(全)
aws codeguru-reviewer list-recommendations \
  --code-review-arn $CODE_REVIEW_ARN

# CRITICAL のみフィルタ
aws codeguru-reviewer list-recommendations \
  --code-review-arn $CODE_REVIEW_ARN \
  --query 'RecommendationSummaries[?Severity==`Critical`].[FilePath,LineNumber,Title]' \
  --output table

# HIGH・CRITICAL カウント
aws codeguru-reviewer list-recommendations \
  --code-review-arn $CODE_REVIEW_ARN \
  --output json | \
jq '.RecommendationSummaries | group_by(.Severity) | map({severity:.[0].Severity, count:length})'

3. オンデマンド解析実行(全リポジトリスキャン)

# Code Review 作成(RepositoryAnalysis)
aws codeguru-reviewer create-code-review \
  --name "manual-scan-$(date +%Y%m%d-%H%M%S)" \
  --repository-association-arn arn:aws:codeguru-reviewer:ap-northeast-1:123456789012:association/... \
  --type RepositoryAnalysis='{
    "RepositoryHead": {"BranchName": "main"}
  }' \
  --region ap-northeast-1

# 返り値
{
  "CodeReviewArn": "arn:aws:codeguru-reviewer:ap-northeast-1:123456789012:code-review/...",
  "RepositoryAssociationArn": "arn:aws:codeguru-reviewer:ap-northeast-1:123456789012:association/..."
}

# Status 監視(Pending → Completed)
CODE_REVIEW_ARN="arn:aws:codeguru-reviewer:ap-northeast-1:123456789012:code-review/..."

while true; do
  STATE=$(aws codeguru-reviewer describe-code-review \
    --code-review-arn $CODE_REVIEW_ARN \
    --query 'CodeReview.State' \
    --output text)
  
  echo "State: $STATE"
  
  if [ "$STATE" = "Completed" ] || [ "$STATE" = "Failed" ]; then
    break
  fi
  
  sleep 10
done

4. Secrets Detection 専用チェック

# Secrets は CodeGuru 自動検出の一部
# 別途 detect-code-violations で直接チェック可能(Detector ごと)

# 全 Recommendations から Secret detector のみ抽出
aws codeguru-reviewer list-recommendations \
  --code-review-arn $CODE_REVIEW_ARN \
  --query 'RecommendationSummaries[?Category==`Security` && Title like `*credential*`]' \
  --output table

5. Association 削除・リセット

# Association 確認
ASSOC_ARN=$(aws codeguru-reviewer list-repository-associations \
  --query 'RepositoryAssociations[0].RepositoryAssociationArn' \
  --output text)

# Disassociate(CodeGuru が PR 解析を停止)
aws codeguru-reviewer disassociate-repository \
  --association-arn $ASSOC_ARN

# State が Disassociated に変更される
# 再度 Associate すれば再開可能

SDK / Infrastructure as Code(5 パターン)

1. CloudFormation での Associate 自動化

AWSTemplateFormatVersion: '2010-09-09'

Resources:
  GitHubRepositoryAssociation:
    Type: AWS::CodeGuruReviewer::RepositoryAssociation
    Properties:
      RepositoryName: myorg/myapp
      Type: GitHub

Outputs:
  AssociationArn:
    Value: !GetAtt GitHubRepositoryAssociation.Arn

2. Python SDK(Boto3)での結果取得・ダッシュボード生成

import boto3
import json
from datetime import datetime

def generate_codeguru_report(code_review_arn):
    """CodeGuru 結果レポート生成"""
    codeguru = boto3.client('codeguru-reviewer')
    
    # Code Review 情報
    review = codeguru.describe_code_review(CodeReviewArn=code_review_arn)['CodeReview']
    
    # Recommendations 取得
    recommendations = codeguru.list_recommendations(CodeReviewArn=code_review_arn)
    
    # サマリー集計
    severity_counts = {}
    category_counts = {}
    
    for rec in recommendations.get('RecommendationSummaries', []):
        severity = rec['Severity']
        category = rec['Category']
        
        severity_counts[severity] = severity_counts.get(severity, 0) + 1
        category_counts[category] = category_counts.get(category, 0) + 1
    
    # レポート生成
    report = {
        'timestamp': datetime.now().isoformat(),
        'codeReviewArn': code_review_arn,
        'state': review['State'],
        'totalRecommendations': len(recommendations.get('RecommendationSummaries', [])),
        'bySeverity': severity_counts,
        'byCategory': category_counts,
        'detailedFindings': [
            {
                'severity': rec['Severity'],
                'category': rec['Category'],
                'title': rec['Title'],
                'file': rec['FilePath'],
                'line': rec['LineNumber']
            }
            for rec in recommendations.get('RecommendationSummaries', [])
            if rec['Severity'] in ['Critical', 'High']
        ]
    }
    
    print(json.dumps(report, indent=2))
    return report

if __name__ == '__main__':
    generate_codeguru_report('arn:aws:codeguru-reviewer:ap-northeast-1:123456789012:code-review/...')

3. Terraform での Repository Association

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_codegurureviewer_repository_association" "example" {
  repository {
    codecommit {
      name = aws_codecommit_repository.example.repository_name
    }
  }

  tags = {
    Team = "DevOps"
    Env  = "Prod"
  }
}

output "association_arn" {
  value = aws_codegurureviewer_repository_association.example.arn
}

4. CDK(TypeScript)での自動化

import * as cdk from 'aws-cdk-lib';
import * as codeguru from 'aws-cdk-lib/aws-codegurureviewer';

export class CodeGuruStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    new codeguru.CfnRepositoryAssociation(this, 'GitHubAssociation', {
      type: 'GitHub',
      repositories: {
        github: {
          name: 'myorg/myapp',
        },
      },
      tags: {
        Team: 'DevOps',
        Environment: 'Production',
      },
    });
  }
}

5. Lambda + EventBridge での定期スキャン自動化

import boto3
import json
from datetime import datetime

codeguru = boto3.client('codeguru-reviewer')
cloudwatch = boto3.client('cloudwatch')

def lambda_handler(event, context):
    """
    EventBridge トリガー:毎週月曜 09:00 UTC に実行
    全リポジトリを CodeGuru でスキャン
    """
    
    # 全 Repository Association を取得
    associations = codeguru.list_repository_associations()
    
    scan_results = []
    
    for assoc in associations.get('RepositoryAssociations', []):
        if assoc['State'] != 'Associated':
            continue
        
        repo_name = assoc['RepositoryName']
        assoc_arn = assoc['RepositoryAssociationArn']
        
        print(f"Scanning: {repo_name}")
        
        # Code Review を作成(RepositoryAnalysis = フル解析)
        try:
            review = codeguru.create_code_review(
                name=f"weekly-scan-{repo_name.replace('/', '-')}-{datetime.now().strftime('%Y%m%d')}",
                repositoryAssociationArn=assoc_arn,
                type='RepositoryAnalysis',
                config={
                    'RepositoryHead': {
                        'BranchName': 'main'
                    }
                }
            )
            
            scan_results.append({
                'repository': repo_name,
                'codeReviewArn': review['CodeReviewArn'],
                'status': 'started'
            })
        except Exception as e:
            print(f"Error scanning {repo_name}: {str(e)}")
            scan_results.append({
                'repository': repo_name,
                'status': 'failed',
                'error': str(e)
            })
    
    # CloudWatch Metric に記録
    cloudwatch.put_metric_data(
        Namespace='CodeGuru',
        MetricData=[
            {
                'MetricName': 'WeeklyScansStarted',
                'Value': len([r for r in scan_results if r['status'] == 'started']),
                'Unit': 'Count'
            },
            {
                'MetricName': 'WeeklyScansFailed',
                'Value': len([r for r in scan_results if r['status'] == 'failed']),
                'Unit': 'Count'
            }
        ]
    )
    
    return {
        'statusCode': 200,
        'body': json.dumps(scan_results)
    }

類似サービス比較表

観点 CodeGuru Reviewer CodeGuru Security GitHub Copilot SonarQube Snyk Code
対応言語 Java / Python 8言語 30+ 30+ 20+
検出基準 AWS + ML OWASP / CWE コード生成 カスタムルール OWASP / CWE
セキュリティ特化 部分的 可能
PR コメント
IDE プラグイン
AWS SDK 検出
Secrets 検出 ✅ 無料
料金 $10/100k行 $0.01/100行 有料 OSS無料 / $150+/月 $250+/月
推奨用途 AWS + Java/Python 多言語セキュリティ コード補完 エンタープライズ DevSecOps

End-of-Life 移行戦略

⚠️ End-of-Life: 2025-04-30

影響範囲

  • 新規 Repository Association 作成不可
  • 既存 Association は 2025-06 まで機能
  • PR 自動レビューは段階的に廃止

移行先

1. CodeGuru Security(推奨)

# CodeGuru Security への移行
# 対応言語: Java / Python / JavaScript / TypeScript / C# / Go / Ruby / Rust
# IDE プラグイン: VS Code / JetBrains
# CI/CD: CodePipeline / GitHub Actions / GitLab CI

2. Amazon Q Developer

# Amazon Q in IDE
# - IDE でのリアルタイムコード生成・修正提案
# - PR レビューコメント自動生成
# - ベストプラクティス提案

移行チェックリスト

  • [ ] 現在の CodeGuru Reviewer Association を確認
  • [ ] CodeGuru Security への対応言語変換(Java/Python → 8 言語対応)
  • [ ] IDE プラグイン VS Code / JetBrains インストール
  • [ ] GitHub Actions での CodeGuru Security ワークフロー構築
  • [ ] CodePipeline での Quality Gate 見直し(CodeGuru Security に更新)
  • [ ] チーム教育・ドキュメント更新
  • [ ] 本番移行日を 2025-05-01 に設定

2025-2026 最新動向

1. CodeGuru Security + Q Developer の統合

2026 上半期 GA 予定

  • PR で CodeGuru Security の脆弱性検出
  • Amazon Q が自動修正提案
  • ワンクリック修正適用

2. Multi-Repository スキャン

2026 計画

  • 複数リポジトリを一度に分析
  • 相互依存関係の脆弱性検出

3. Container Image スキャン

2025-2026 ロードマップ

  • Docker / OCI イメージの脆弱性検出
  • ECR との統合

学習リソース・参考文献

AWS 公式

  1. Amazon CodeGuru Reviewer User Guide

  2. CodeGuru Reviewer API Reference

  3. CodeGuru Detector Library

  4. CodeGuru Reviewer Availability Change

オープンソース・ベンダー

  1. SonarQube Community Edition

  2. Semgrep OSS

  3. AWS Samples(CodeGuru + CodePipeline)


実装例・チェックリスト

実装例:GitHub PR + CodeGuru Reviewer 統合

#!/bin/bash
set -e

GITHUB_ORG="myorg"
GITHUB_REPO="myapp"
REGION="ap-northeast-1"

# Step 1: Repository Association
echo "Creating CodeGuru Repository Association..."
ASSOC_ARN=$(aws codeguru-reviewer associate-repository \
  --repository GitHub='{"Name": "'$GITHUB_ORG'/'$GITHUB_REPO'"}' \
  --region $REGION \
  --query 'RepositoryAssociation.RepositoryAssociationArn' \
  --output text)

echo "Associated: $ASSOC_ARN"
echo "CodeGuru will now automatically review GitHub PRs."
echo ""
echo "Test: Create a test PR with intentional issues"
echo "  - Hardcoded AWS credentials"
echo "  - Resource leak (no file close)"
echo "  - Weak cryptography (MD5)"

採用チェックリスト

  • [ ] Java / Python コードが主体か
  • [ ] GitHub / GitLab / Bitbucket / CodeCommit を使用しているか
  • [ ] PR ベースのレビュープロセスか
  • [ ] AWS SDK の使用頻度が高いか
  • [ ] セキュリティ監査が必須か
  • [ ] CodePipeline での品質ゲートが必要か
  • [ ] End-of-Life 対応の準備状況(2025-04 以降)
  • [ ] CodeGuru Security への移行計画があるか

まとめ

Amazon CodeGuru Reviewer は 「Java・Python コードの ML ベース自動 PR レビューサービス」。GitHub など外部リポジトリの PR に直接コメントを投稿し、セキュリティ脆弱性・リソースリーク・AWS ベストプラクティス違反を検出する。Secrets Detection で認証情報ハードコーディングを無料検出でき、CodePipeline のゲートとして品質をブロック。ただし 2025-04-30 の End-of-Life に伴い、セキュリティ機能は CodeGuru Security・Q Developer に統合される。新規採用では CodeGuru Security を優先推奨。既存ユーザーは 2025-05-01 までに移行を完了する必要がある


最終更新:2026-04-26 バージョン:v2.0