aws-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS Development Best Practices

AWS开发最佳实践

Overview

概述

This skill provides comprehensive guidelines for developing applications on Amazon Web Services (AWS), focusing on serverless architecture, Infrastructure as Code, and security best practices.
本技能提供了在亚马逊云科技(AWS)上开发应用的全面指南,重点关注无服务器架构、基础设施即代码(Infrastructure as Code)以及安全最佳实践。

Core Principles

核心原则

  • Write clean, well-structured code with accurate AWS SDK examples
  • Use Infrastructure as Code (Terraform, CDK, SAM) for all infrastructure
  • Follow the principle of least privilege for all IAM policies
  • Implement comprehensive logging, metrics, and tracing for observability
  • 编写清晰、结构良好的代码,并提供准确的AWS SDK示例
  • 使用基础设施即代码(Terraform、CDK、SAM)管理所有基础设施
  • 为所有IAM策略遵循最小权限原则
  • 实现全面的日志、指标和追踪以保障可观测性

AWS Lambda Guidelines

AWS Lambda指南

Configuration Standards

配置标准

  • Use TypeScript implementation on ARM64 architecture for better performance and cost
  • Set appropriate memory and timeout values based on workload requirements
  • Use environment variables for configuration, never hardcode values
  • Implement proper error handling and retry logic
  • 使用ARM64架构的TypeScript实现以获得更好的性能和成本效益
  • 根据工作负载需求设置合适的内存和超时值
  • 使用环境变量存储配置,切勿硬编码值
  • 实现适当的错误处理和重试逻辑

Lambda Best Practices

Lambda最佳实践

typescript
// Use ES modules and typed handlers
import { APIGatewayProxyHandler } from 'aws-lambda';

export const handler: APIGatewayProxyHandler = async (event) => {
  try {
    // Validate input at function start
    if (!event.body) {
      return { statusCode: 400, body: JSON.stringify({ error: 'Missing body' }) };
    }

    // Business logic here

    return { statusCode: 200, body: JSON.stringify({ success: true }) };
  } catch (error) {
    console.error('Lambda error:', error);
    return { statusCode: 500, body: JSON.stringify({ error: 'Internal error' }) };
  }
};
typescript
// Use ES modules and typed handlers
import { APIGatewayProxyHandler } from 'aws-lambda';

export const handler: APIGatewayProxyHandler = async (event) => {
  try {
    // Validate input at function start
    if (!event.body) {
      return { statusCode: 400, body: JSON.stringify({ error: 'Missing body' }) };
    }

    // Business logic here

    return { statusCode: 200, body: JSON.stringify({ success: true }) };
  } catch (error) {
    console.error('Lambda error:', error);
    return { statusCode: 500, body: JSON.stringify({ error: 'Internal error' }) };
  }
};

AWS CDK Guidelines

AWS CDK指南

Implementation Standards

实现标准

  • Use
    aws-cdk-lib
    with explicit
    aws_*
    prefixes
  • Implement custom constructs for reusable patterns
  • Separate concerns into distinct CloudFormation stacks
  • Organize resources by functional groups: storage, compute, authentication, API, access
  • 使用带明确
    aws_*
    前缀的
    aws-cdk-lib
  • 为可复用模式实现自定义构造(Construct)
  • 将关注点分离到不同的CloudFormation栈中
  • 按功能组组织资源:存储、计算、认证、API、访问

Project Structure

项目结构

aws/
├── constructs/     # CDK custom constructs
├── stacks/         # CloudFormation stack definitions
├── functions/      # Lambda function implementations
└── tests/          # Infrastructure tests
aws/
├── constructs/     # CDK custom constructs
├── stacks/         # CloudFormation stack definitions
├── functions/      # Lambda function implementations
└── tests/          # Infrastructure tests

CDK Best Practices

CDK最佳实践

typescript
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws_lambda';
import * as dynamodb from 'aws-cdk-lib/aws_dynamodb';

// Use custom constructs for reusable patterns
export class ApiConstruct extends Construct {
  constructor(scope: Construct, id: string, props: ApiProps) {
    super(scope, id);
    // Implementation
  }
}
typescript
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws_lambda';
import * as dynamodb from 'aws-cdk-lib/aws_dynamodb';

// Use custom constructs for reusable patterns
export class ApiConstruct extends Construct {
  constructor(scope: Construct, id: string, props: ApiProps) {
    super(scope, id);
    // Implementation
  }
}

DynamoDB Patterns

DynamoDB模式

Table Design

表设计

  • Design tables around access patterns, not entity relationships
  • Use single-table design when appropriate
  • Implement GSIs for additional access patterns
  • Use on-demand capacity for variable workloads, provisioned for predictable
  • 围绕访问模式而非实体关系设计表
  • 适当时使用单表设计
  • 为额外的访问模式实现全局二级索引(GSI)
  • 可变工作负载使用按需容量模式,可预测工作负载使用预置容量模式

Best Practices

最佳实践

  • Always use strongly typed item definitions
  • Implement optimistic locking with version attributes
  • Use batch operations for multiple items
  • Enable point-in-time recovery for production tables
  • 始终使用强类型的条目定义
  • 利用版本属性实现乐观锁
  • 对多个条目使用批量操作
  • 为生产表启用点-in-time恢复(Point-in-Time Recovery)

IAM Security Best Practices

IAM安全最佳实践

Principles

原则

  • Apply least privilege: grant only permissions needed
  • Use IAM roles, not access keys, for AWS service access
  • Implement resource-based policies where appropriate
  • Regular audit and rotate credentials
  • 应用最小权限原则:仅授予所需的权限
  • 使用IAM角色而非访问密钥供AWS服务访问
  • 适当时实现基于资源的策略
  • 定期审计并轮换凭证

Policy Example

策略示例

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Query"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/MyTable"
    }
  ]
}
json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Query"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/MyTable"
    }
  ]
}

SAM Template Configuration

SAM模板配置

Template Structure

模板结构

yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 30
    Runtime: nodejs20.x
    Architectures:
      - arm64
    Tracing: Active

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: index.handler
      Events:
        Api:
          Type: Api
          Properties:
            Path: /items
            Method: GET
yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 30
    Runtime: nodejs20.x
    Architectures:
      - arm64
    Tracing: Active

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: index.handler
      Events:
        Api:
          Type: Api
          Properties:
            Path: /items
            Method: GET

API Gateway Configuration

API网关配置

Best Practices

最佳实践

  • Use Cognito or IAM for authentication
  • Implement request validation
  • Enable CORS only when necessary
  • Use usage plans and API keys for rate limiting
  • 使用Cognito或IAM进行认证
  • 实现请求验证
  • 仅在必要时启用CORS
  • 使用使用计划和API密钥进行速率限制

Step Functions for Orchestration

Step Functions编排

  • Use Step Functions for complex workflows
  • Implement error handling with Catch and Retry
  • Use Express workflows for high-volume, short-duration
  • Use Standard workflows for long-running processes
  • 使用Step Functions处理复杂工作流
  • 通过Catch和Retry实现错误处理
  • 针对高容量、短持续时间的场景使用Express工作流
  • 针对长时间运行的流程使用Standard工作流

Security Standards

安全标准

Encryption

加密

  • Enable encryption at rest for all storage services
  • Use AWS KMS for key management
  • Enable encryption in transit (TLS)
  • Use custom KMS keys for sensitive data
  • 为所有存储服务启用静态加密
  • 使用AWS KMS进行密钥管理
  • 启用传输中加密(TLS)
  • 对敏感数据使用自定义KMS密钥

Secrets Management

密钥管理

  • Store secrets in AWS Secrets Manager or Parameter Store
  • Never commit secrets to version control
  • Rotate secrets automatically
  • Use IAM roles to access secrets
  • 将密钥存储在AWS Secrets Manager或Parameter Store中
  • 切勿将密钥提交到版本控制系统
  • 自动轮换密钥
  • 使用IAM角色访问密钥

Observability

可观测性

Logging

日志

  • Use structured JSON logging
  • Include correlation IDs across services
  • Log at appropriate levels (INFO, WARN, ERROR)
  • Enable CloudWatch Logs Insights for querying
  • 使用结构化JSON日志
  • 在各服务间包含关联ID
  • 按适当级别记录日志(INFO、WARN、ERROR)
  • 启用CloudWatch Logs Insights以进行查询

Monitoring

监控

  • Create CloudWatch alarms for critical metrics
  • Use X-Ray for distributed tracing
  • Implement custom metrics for business KPIs
  • Set up dashboards for operational visibility
  • 为关键指标创建CloudWatch告警
  • 使用X-Ray进行分布式追踪
  • 为业务关键绩效指标(KPI)实现自定义指标
  • 设置仪表板以提升运营可见性

Testing

测试

Unit Testing

单元测试

  • Mock AWS SDK calls in unit tests
  • Use localstack or SAM local for integration testing
  • Test IAM policies with policy simulator
  • Validate CloudFormation/CDK with cfn-lint
  • 在单元测试中模拟AWS SDK调用
  • 使用localstack或SAM local进行集成测试
  • 使用策略模拟器测试IAM策略
  • 使用cfn-lint验证CloudFormation/CDK

Integration Testing

集成测试

typescript
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { mockClient } from 'aws-sdk-client-mock';

const ddbMock = mockClient(DynamoDBClient);

beforeEach(() => {
  ddbMock.reset();
});

test('handler returns items', async () => {
  ddbMock.on(QueryCommand).resolves({ Items: [] });
  const result = await handler(event);
  expect(result.statusCode).toBe(200);
});
typescript
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { mockClient } from 'aws-sdk-client-mock';

const ddbMock = mockClient(DynamoDBClient);

beforeEach(() => {
  ddbMock.reset();
});

test('handler returns items', async () => {
  ddbMock.on(QueryCommand).resolves({ Items: [] });
  const result = await handler(event);
  expect(result.statusCode).toBe(200);
});

CI/CD Integration

CI/CD集成

  • Use AWS CodePipeline or GitHub Actions for CI/CD
  • Run
    cdk diff
    or
    sam validate
    before deployment
  • Implement staging environments (dev, staging, prod)
  • Use parameter overrides for environment-specific config
  • 使用AWS CodePipeline或GitHub Actions实现CI/CD
  • 部署前运行
    cdk diff
    sam validate
  • 实现 staging 环境(开发、预发布、生产)
  • 使用参数覆盖实现环境特定配置

Common Pitfalls to Avoid

需避免的常见陷阱

  1. Hardcoding AWS credentials or secrets
  2. Not setting appropriate Lambda timeouts
  3. Ignoring cold start optimization
  4. Over-provisioning resources
  5. Not implementing proper error handling
  6. Missing CloudWatch alarms
  7. Inadequate IAM policies (too permissive)
  8. Not using VPC when required for compliance
  1. 硬编码AWS凭证或密钥
  2. 未设置适当的Lambda超时时间
  3. 忽略冷启动优化
  4. 过度配置资源
  5. 未实现适当的错误处理
  6. 缺失CloudWatch告警
  7. IAM策略权限过大
  8. 合规要求需要时未使用VPC