Amazon CodeWhisperer (Amazon Q Developer)
AIツール
Amazon CodeWhisperer (Amazon Q Developer)
概要
Amazon CodeWhisperer(現在はAmazon Q Developerにリブランド)は、AWSが開発したAIコード生成・補完ツールです。15のプログラミング言語をサポートし、VS Code、IntelliJ、AWS Cloud9などの主要IDEと統合できます。リアルタイムコード提案、セキュリティスキャン、参照追跡機能を提供し、AWS生態系との深い統合により企業向け開発を強力にサポートします。
詳細
Amazon CodeWhispererは2023年に一般提供を開始し、2025年にAmazon Q Developerとして進化しました。最新版では、SWE-Benchリーダーボードで最高スコアを記録するAIエージェント機能、Model Context Protocol (MCP) サポート、AI駆動の多段階タスク実行機能を搭載しています。AWS生態系との統合により、企業レベルのセキュリティとコンプライアンスを維持しながら開発効率を大幅に向上させます。
主要技術特徴
- リアルタイムコード提案: コンテキストを理解した高精度なコード生成
- セキュリティスキャン: コード生成時の自動セキュリティ脆弱性検出
- 参照追跡: オープンソースライセンス準拠とコード出典の透明性
- AWS統合: AWSサービスとの深い連携とベストプラクティス提案
- エンタープライズ対応: IAM制御、コンプライアンス、監査ログ完備
最新機能(2025年Amazon Q Developer版)
- AIエージェント機能: SWE-Benchベンチマークで業界最高スコア達成
- Model Context Protocol (MCP): カスタムツールとサービス連携強化
- 多段階タスク実行: 複雑な開発タスクの自動化
- リポジトリ統合: 企業コードベースとの高度なコンテキスト認識
- 強化セキュリティ: AWS GuardDuty連携によるリアルタイム脅威検出
メリット・デメリット
メリット
- AWS生態系統合: AWS開発環境での最適化されたユーザー体験
- 企業向けセキュリティ: IAM制御、コンプライアンス、監査ログ完備
- 高いコード受容率: 業界平均を上回るコード提案の採用率
- 無料個人プラン: 基本機能を個人開発者が無料利用可能
- 参照追跡: オープンソースライセンス違反リスクの自動検出
- 多言語対応: Python、Java、JavaScript等15言語の包括サポート
デメリット
- AWS中心ワークフロー: AWS以外のクラウド環境での機能制限
- 限定的な無料プラン: 高度な機能は有料プラン必須
- 企業向け価格: エンタープライズ機能のコストが高額
- 学習曲線: AWS生態系の理解が効果的な活用に必要
- 競合比較: GitHub CopilotやCodeiumと比較して後発
参考ページ
書き方の例
VS Codeでのセットアップ
# VS Code拡張機能のインストール
# 1. VS Code Extensions (Ctrl+Shift+X) を開く
# 2. "AWS Toolkit" を検索してインストール
# 3. Amazon Q extension も併せてインストール
# 4. AWS Builder ID または IAM Identity Centerでサインイン
# コマンドラインでのインストール
code --install-extension amazonwebservices.aws-toolkit-vscode
code --install-extension amazonwebservices.amazon-q-vscode
AWS Builder IDでの認証
# AWS CLI設定(Builder ID使用)
aws configure sso
# SSO セッション名: my-dev-session
# SSO start URL: https://d-xxxxxxxxxx.awsapps.com/start
# SSO region: us-east-1
# SSO registration scopes: sso:account:access
# 認証完了後、VS CodeでAWS: Connect with AWS Builder IDを実行
IntelliJ IDEA / PyCharmでのセットアップ
# JetBrains IDEでのプラグインインストール
# 1. Settings > Plugins を開く
# 2. Marketplace で "AWS Toolkit" を検索
# 3. インストール後、IDEを再起動
# 4. AWS Explorer で Builder ID認証を実行
# Gradle/Mavenプロジェクトでの設定
# build.gradle または pom.xml にAWS SDK依存関係を追加
Python での基本的なコード生成
# Amazon Q Developer を使った AWS SDK 活用例
# コメントを書くと、CodeWhispererが実装を提案
import boto3
from botocore.exceptions import ClientError
import json
def create_s3_bucket(bucket_name, region='us-east-1'):
"""S3バケットを作成し、適切なセキュリティ設定を適用"""
# CodeWhispererがAWSベストプラクティスに基づいて実装提案
try:
s3_client = boto3.client('s3', region_name=region)
# バケット作成(リージョン指定)
if region == 'us-east-1':
s3_client.create_bucket(Bucket=bucket_name)
else:
s3_client.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': region}
)
# バケットのパブリックアクセスをブロック(セキュリティベストプラクティス)
s3_client.put_public_access_block(
Bucket=bucket_name,
PublicAccessBlockConfiguration={
'BlockPublicAcls': True,
'IgnorePublicAcls': True,
'BlockPublicPolicy': True,
'RestrictPublicBuckets': True
}
)
# サーバーサイド暗号化の有効化
s3_client.put_bucket_encryption(
Bucket=bucket_name,
ServerSideEncryptionConfiguration={
'Rules': [
{
'ApplyServerSideEncryptionByDefault': {
'SSEAlgorithm': 'AES256'
},
'BucketKeyEnabled': True
}
]
}
)
print(f"S3バケット '{bucket_name}' を正常に作成しました")
return True
except ClientError as e:
print(f"S3バケット作成エラー: {e}")
return False
# DynamoDBテーブル操作の例
def create_dynamodb_table(table_name):
"""DynamoDBテーブルを作成し、基本的な設定を適用"""
try:
dynamodb = boto3.resource('dynamodb')
# CodeWhispererがDynamoDBベストプラクティスを提案
table = dynamodb.create_table(
TableName=table_name,
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
}
],
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S'
}
],
BillingMode='PAY_PER_REQUEST', # オンデマンド課金
DeletionProtectionEnabled=True, # 削除保護
Tags=[
{
'Key': 'Environment',
'Value': 'production'
},
{
'Key': 'Application',
'Value': 'web-reference'
}
]
)
# テーブル作成完了まで待機
table.wait_until_exists()
print(f"DynamoDBテーブル '{table_name}' を正常に作成しました")
return table
except ClientError as e:
print(f"DynamoDBテーブル作成エラー: {e}")
return None
JavaScript/Node.js での AWS Lambda 関数
// AWS Lambda 関数開発での CodeWhisperer 活用例
const AWS = require('aws-sdk');
// CodeWhispererがLambdaベストプラクティスを提案
exports.handler = async (event, context) => {
// AWS X-Ray分散トレーシングの設定
const AWSXRay = require('aws-xray-sdk-core');
const aws = AWSXRay.captureAWS(AWS);
const dynamodb = new aws.DynamoDB.DocumentClient();
const s3 = new aws.S3();
try {
// CloudWatch Logsへの構造化ログ出力
console.log(JSON.stringify({
level: 'INFO',
timestamp: new Date().toISOString(),
requestId: context.awsRequestId,
event: event
}));
// DynamoDB操作の例
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id
}
};
const result = await dynamodb.get(params).promise();
if (!result.Item) {
return {
statusCode: 404,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,Authorization',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS'
},
body: JSON.stringify({
error: 'Item not found',
requestId: context.awsRequestId
})
};
}
// 成功レスポンス
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
data: result.Item,
requestId: context.awsRequestId
})
};
} catch (error) {
// エラーログの出力
console.error(JSON.stringify({
level: 'ERROR',
timestamp: new Date().toISOString(),
requestId: context.awsRequestId,
error: error.message,
stack: error.stack
}));
return {
statusCode: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'Internal server error',
requestId: context.awsRequestId
})
};
}
};
セキュリティスキャンと修正提案
# セキュリティ脆弱性のあるコード例
# CodeWhispererが自動で問題を検出し、修正を提案
# ❌ セキュリティ問題のあるコード
def insecure_database_query(user_id):
import sqlite3
conn = sqlite3.connect('users.db')
# SQLインジェクション脆弱性
query = f"SELECT * FROM users WHERE id = {user_id}"
result = conn.execute(query).fetchone()
conn.close()
return result
# ✅ CodeWhispererが提案する修正版
def secure_database_query(user_id):
import sqlite3
from typing import Optional, Dict, Any
try:
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row # 辞書形式でアクセス可能
# パラメータ化クエリでSQLインジェクション対策
query = "SELECT * FROM users WHERE id = ?"
result = conn.execute(query, (user_id,)).fetchone()
if result:
return dict(result)
return None
except sqlite3.Error as e:
print(f"Database error: {e}")
return None
finally:
if conn:
conn.close()
# AWS Secrets Manager での機密情報管理
def get_database_credentials():
"""AWS Secrets Managerから安全にDB認証情報を取得"""
import boto3
import json
secret_name = "prod/database/credentials"
region_name = "us-east-1"
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
response = client.get_secret_value(SecretId=secret_name)
secret = json.loads(response['SecretString'])
return {
'host': secret['host'],
'username': secret['username'],
'password': secret['password'],
'database': secret['database']
}
except ClientError as e:
print(f"Secrets Manager error: {e}")
return None
Infrastructure as Code(CloudFormation)
# CloudFormation テンプレートでの CodeWhisperer 活用
# YAML コメントから適切なリソース定義を生成
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Web Reference App Infrastructure'
Parameters:
Environment:
Type: String
Default: production
AllowedValues: [development, staging, production]
Resources:
# CodeWhispererがセキュリティベストプラクティスに基づいて提案
S3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub 'web-reference-${Environment}-${AWS::AccountId}'
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
BucketKeyEnabled: true
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
LoggingConfiguration:
DestinationBucketName: !Ref AccessLogsBucket
LogFilePrefix: access-logs/
NotificationConfiguration:
CloudWatchConfigurations:
- Event: s3:ObjectCreated:*
CloudWatchConfiguration:
LogGroupName: !Ref CloudWatchLogGroup
# DynamoDBテーブル(セキュリティ設定込み)
DynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub 'web-reference-${Environment}'
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: true
DeletionProtectionEnabled: true
SSESpecification:
SSEEnabled: true
KMSMasterKeyId: alias/aws/dynamodb
Tags:
- Key: Environment
Value: !Ref Environment
- Key: Application
Value: web-reference
# Lambda関数(セキュリティロール付き)
WebReferenceFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub 'web-reference-api-${Environment}'
Runtime: nodejs18.x
Handler: index.handler
Code:
ZipFile: |
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!')
};
};
Environment:
Variables:
DYNAMODB_TABLE: !Ref DynamoDBTable
ENVIRONMENT: !Ref Environment
ReservedConcurrencyLimit: 10
DeadLetterQueue:
TargetArn: !GetAtt DeadLetterQueue.Arn
TracingConfig:
Mode: Active
企業向けガバナンス設定
{
"codewhisperer": {
"enterprise": {
"enabled": true,
"organization": "web-reference-corp",
"sso_provider": "aws_sso",
"iam_roles": {
"developers": "arn:aws:iam::123456789012:role/CodeWhispererDeveloper",
"admin": "arn:aws:iam::123456789012:role/CodeWhispererAdmin"
}
},
"security": {
"scan_enabled": true,
"reference_tracking": true,
"blocked_suggestions": [
"hardcoded_secrets",
"sql_injection",
"xss_vulnerabilities",
"insecure_crypto"
],
"compliance_mode": "strict"
},
"customization": {
"repository_indexing": true,
"custom_libraries": [
"internal-company-framework",
"proprietary-security-lib"
],
"code_standards": "company-style-guide.json"
},
"monitoring": {
"usage_analytics": true,
"audit_logging": true,
"cloudtrail_integration": true,
"cost_allocation_tags": {
"Department": "Engineering",
"Project": "WebReference",
"CostCenter": "Development"
}
}
}
}
Amazon Q Developerエージェント機能
# Amazon Q Developer Agentを使った複雑なタスク自動化
# VS Code内でのコマンドパレット(Ctrl+Shift+P)
# 1. "Amazon Q: Open Chat" を実行
# 2. エージェント機能での指示例:
# 複雑なタスクの例:
/dev "Express.js APIサーバーを作成して、以下の要件を満たしてください:
1. JWT認証機能
2. PostgreSQL接続とPrisma ORM統合
3. API Rate Limiting
4. OpenAPI/Swagger文書生成
5. Jest単体テスト
6. Docker化
7. AWS ECS用のTaskDefinition作成"
# Q Developerエージェントが段階的に実行:
# ✓ package.jsonとプロジェクト構造作成
# ✓ Express.jsサーバー基盤実装
# ✓ JWT認証ミドルウェア実装
# ✓ Prisma設定とスキーマ定義
# ✓ API Rate Limitingの設定
# ✓ Swagger設定ファイル作成
# ✓ Jest設定とテストファイル作成
# ✓ Dockerfile作成
# ✓ ECS TaskDefinition JSON作成
# 進行状況の確認
# プロジェクトエクスプローラーで生成されたファイル構造を確認
# "Amazon Q: Show Agent Activity" で実行状況確認