Amazon CodeWhisperer (Amazon Q Developer)

AI DevelopmentAWS IntegrationSecurity ScanningEnterpriseReal-time Completion

AI Tool

Amazon CodeWhisperer (Amazon Q Developer)

Overview

Amazon CodeWhisperer (now rebranded as Amazon Q Developer) is an AI code generation and completion tool developed by AWS. It supports 15 programming languages and integrates with major IDEs including VS Code, IntelliJ, and AWS Cloud9. Providing real-time code suggestions, security scanning, and reference tracking capabilities, it strongly supports enterprise development through deep integration with the AWS ecosystem.

Details

Amazon CodeWhisperer began general availability in 2023 and evolved into Amazon Q Developer in 2025. The latest version features AI agent functionality that achieved the highest score on the SWE-Bench leaderboard, Model Context Protocol (MCP) support, and AI-driven multi-step task execution capabilities. Through integration with the AWS ecosystem, it dramatically improves development efficiency while maintaining enterprise-level security and compliance.

Key Technical Features

  • Real-time Code Suggestions: High-precision code generation with contextual understanding
  • Security Scanning: Automatic security vulnerability detection during code generation
  • Reference Tracking: Open-source license compliance and code provenance transparency
  • AWS Integration: Deep collaboration with AWS services and best practice suggestions
  • Enterprise Ready: Complete IAM controls, compliance, and audit logging

Latest Features (2025 Amazon Q Developer Edition)

  • AI Agent Functionality: Achieved industry-leading scores on SWE-Bench benchmark
  • Model Context Protocol (MCP): Enhanced custom tool and service integration
  • Multi-step Task Execution: Automation of complex development tasks
  • Repository Integration: Advanced contextual awareness with enterprise codebases
  • Enhanced Security: Real-time threat detection through AWS GuardDuty integration

Advantages and Disadvantages

Advantages

  • AWS Ecosystem Integration: Optimized user experience in AWS development environments
  • Enterprise Security: Complete IAM controls, compliance, and audit logging
  • High Code Acceptance Rate: Above-industry-average adoption rate for code suggestions
  • Free Individual Plan: Basic functionality available free for individual developers
  • Reference Tracking: Automatic detection of open-source license violation risks
  • Multi-language Support: Comprehensive support for 15 languages including Python, Java, JavaScript

Disadvantages

  • AWS-centric Workflow: Feature limitations in non-AWS cloud environments
  • Limited Free Plan: Advanced features require paid subscription
  • Enterprise Pricing: High costs for enterprise functionality
  • Learning Curve: AWS ecosystem understanding required for effective utilization
  • Competitive Comparison: Later entry compared to GitHub Copilot and Codeium

Reference Links

Code Examples

VS Code Setup

# Install VS Code extension
# 1. Open VS Code Extensions (Ctrl+Shift+X)
# 2. Search for "AWS Toolkit" and install
# 3. Also install Amazon Q extension
# 4. Sign in with AWS Builder ID or IAM Identity Center

# Command line installation
code --install-extension amazonwebservices.aws-toolkit-vscode
code --install-extension amazonwebservices.amazon-q-vscode

AWS Builder ID Authentication

# AWS CLI setup (using Builder ID)
aws configure sso

# SSO session name: my-dev-session
# SSO start URL: https://d-xxxxxxxxxx.awsapps.com/start
# SSO region: us-east-1
# SSO registration scopes: sso:account:access

# After authentication, execute AWS: Connect with AWS Builder ID in VS Code

IntelliJ IDEA / PyCharm Setup

# JetBrains IDE plugin installation
# 1. Open Settings > Plugins
# 2. Search "AWS Toolkit" in Marketplace
# 3. Install and restart IDE
# 4. Execute Builder ID authentication in AWS Explorer

# Gradle/Maven project setup
# Add AWS SDK dependencies to build.gradle or pom.xml

Basic Code Generation in Python

# Example using Amazon Q Developer with AWS SDK
# Write comments and CodeWhisperer suggests implementation

import boto3
from botocore.exceptions import ClientError
import json

def create_s3_bucket(bucket_name, region='us-east-1'):
    """Create S3 bucket with appropriate security settings"""
    # CodeWhisperer suggests implementation based on AWS best practices
    try:
        s3_client = boto3.client('s3', region_name=region)
        
        # Create bucket (with region specification)
        if region == 'us-east-1':
            s3_client.create_bucket(Bucket=bucket_name)
        else:
            s3_client.create_bucket(
                Bucket=bucket_name,
                CreateBucketConfiguration={'LocationConstraint': region}
            )
        
        # Block bucket public access (security best practice)
        s3_client.put_public_access_block(
            Bucket=bucket_name,
            PublicAccessBlockConfiguration={
                'BlockPublicAcls': True,
                'IgnorePublicAcls': True,
                'BlockPublicPolicy': True,
                'RestrictPublicBuckets': True
            }
        )
        
        # Enable server-side encryption
        s3_client.put_bucket_encryption(
            Bucket=bucket_name,
            ServerSideEncryptionConfiguration={
                'Rules': [
                    {
                        'ApplyServerSideEncryptionByDefault': {
                            'SSEAlgorithm': 'AES256'
                        },
                        'BucketKeyEnabled': True
                    }
                ]
            }
        )
        
        print(f"S3 bucket '{bucket_name}' created successfully")
        return True
        
    except ClientError as e:
        print(f"S3 bucket creation error: {e}")
        return False

# DynamoDB table operations example
def create_dynamodb_table(table_name):
    """Create DynamoDB table with basic configuration"""
    try:
        dynamodb = boto3.resource('dynamodb')
        
        # CodeWhisperer suggests DynamoDB best practices
        table = dynamodb.create_table(
            TableName=table_name,
            KeySchema=[
                {
                    'AttributeName': 'id',
                    'KeyType': 'HASH'
                }
            ],
            AttributeDefinitions=[
                {
                    'AttributeName': 'id',
                    'AttributeType': 'S'
                }
            ],
            BillingMode='PAY_PER_REQUEST',  # On-demand billing
            DeletionProtectionEnabled=True,  # Deletion protection
            Tags=[
                {
                    'Key': 'Environment',
                    'Value': 'production'
                },
                {
                    'Key': 'Application',
                    'Value': 'web-reference'
                }
            ]
        )
        
        # Wait until table creation is complete
        table.wait_until_exists()
        
        print(f"DynamoDB table '{table_name}' created successfully")
        return table
        
    except ClientError as e:
        print(f"DynamoDB table creation error: {e}")
        return None

JavaScript/Node.js AWS Lambda Function

// CodeWhisperer utilization example in AWS Lambda function development
const AWS = require('aws-sdk');

// CodeWhisperer suggests Lambda best practices
exports.handler = async (event, context) => {
    // AWS X-Ray distributed tracing setup
    const AWSXRay = require('aws-xray-sdk-core');
    const aws = AWSXRay.captureAWS(AWS);
    
    const dynamodb = new aws.DynamoDB.DocumentClient();
    const s3 = new aws.S3();
    
    try {
        // Structured log output to CloudWatch Logs
        console.log(JSON.stringify({
            level: 'INFO',
            timestamp: new Date().toISOString(),
            requestId: context.awsRequestId,
            event: event
        }));
        
        // DynamoDB operation example
        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
                })
            };
        }
        
        // Success response
        return {
            statusCode: 200,
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            },
            body: JSON.stringify({
                data: result.Item,
                requestId: context.awsRequestId
            })
        };
        
    } catch (error) {
        // Error log output
        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
            })
        };
    }
};

Security Scanning and Remediation Suggestions

# Example of code with security vulnerabilities
# CodeWhisperer automatically detects issues and suggests fixes

# ❌ Code with security issues
def insecure_database_query(user_id):
    import sqlite3
    conn = sqlite3.connect('users.db')
    # SQL injection vulnerability
    query = f"SELECT * FROM users WHERE id = {user_id}"
    result = conn.execute(query).fetchone()
    conn.close()
    return result

# ✅ Fixed version suggested by 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  # Enable dictionary-style access
        
        # Parameterized query to prevent SQL injection
        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()

# Secure credential management with AWS Secrets Manager
def get_database_credentials():
    """Securely retrieve DB credentials from AWS Secrets Manager"""
    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 template utilizing CodeWhisperer
# Generate appropriate resource definitions from YAML comments

AWSTemplateFormatVersion: '2010-09-09'
Description: 'Web Reference App Infrastructure'

Parameters:
  Environment:
    Type: String
    Default: production
    AllowedValues: [development, staging, production]

Resources:
  # CodeWhisperer suggests based on security best practices
  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 table (with security settings)
  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 function (with security role)
  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

Enterprise Governance Configuration

{
  "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 Agent Functionality

# Complex task automation using Amazon Q Developer Agent
# Command Palette in VS Code (Ctrl+Shift+P)

# 1. Execute "Amazon Q: Open Chat"
# 2. Agent functionality instruction examples:

# Complex task example:
/dev "Create an Express.js API server that meets the following requirements:
1. JWT authentication functionality
2. PostgreSQL connection with Prisma ORM integration
3. API Rate Limiting
4. OpenAPI/Swagger documentation generation
5. Jest unit tests
6. Dockerization
7. AWS ECS TaskDefinition creation"

# Q Developer Agent executes step by step:
# ✓ Create package.json and project structure
# ✓ Implement Express.js server foundation
# ✓ Implement JWT authentication middleware
# ✓ Prisma setup and schema definition
# ✓ API Rate Limiting configuration
# ✓ Swagger configuration file creation
# ✓ Jest setup and test file creation
# ✓ Dockerfile creation
# ✓ ECS TaskDefinition JSON creation

# Progress monitoring
# Check generated file structure in Project Explorer
# View execution status with "Amazon Q: Show Agent Activity"