1.1.9 AWS SDKs & APIs

Write Code that Interacts with AWS Services

AWS SDK Credential Resolution Order

SDK tìm credentials theo thứ tự ưu tiên:

PrioritySourceMô tả
1Code (hardcoded)KHÔNG BAO GIỜ dùng trong production
2Environment VariablesAWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
3Shared Credentials File~/.aws/credentials (profiles)
4AWS Config File~/.aws/config
5Container CredentialsECS Task Role
6Instance ProfileEC2 Instance Profile / Lambda Execution Role

AWS SDK Retry & Error Handling

import boto3
from botocore.config import Config
from botocore.exceptions import ClientError

# Configure retry
config = Config(
    retries={
        'max_attempts': 5,
        'mode': 'adaptive'  # standard | adaptive
    },
    connect_timeout=5,
    read_timeout=10
)
client = boto3.client('dynamodb', config=config)

# Handle specific errors
try:
    response = client.get_item(
        TableName='my-table',
        Key={'id': {'S': '123'}}
    )
except ClientError as e:
    error_code = e.response['Error']['Code']
    if error_code == 'ProvisionedThroughputExceededException':
        # Throttling — SDK sẽ tự retry
        pass
    elif error_code == 'ResourceNotFoundException':
        # Table không tồn tại
        pass

Retry Modes

ModeMô tả
LegacyRetry cơ bản, không backoff
StandardExponential backoff + jitter
AdaptiveStandard + client-side rate limiting

AWS CLI (Command Line Interface)

AWS CLI là unified tool để quản lý AWS services từ command line.

Key Features cho Developer

FeatureMô tả
ProfilesMultiple accounts/roles (--profile prod)
Output formatsJSON, YAML, text, table (--output json)
QueryJMESPath filtering (--query 'Items[].id.S')
Pagination--page-size, --max-items, --starting-token
Dry run--dry-run cho EC2 operations
Waitaws ... wait cho async operations

CLI Configuration

# Configure default profile
aws configure
# AWS Access Key ID: AKIA...
# AWS Secret Access Key: ...
# Default region name: us-east-1
# Default output format: json

# Configure named profile
aws configure --profile prod

# Use specific profile
aws s3 ls --profile prod

# Environment variable override
export AWS_PROFILE=prod
export AWS_DEFAULT_REGION=us-east-1

Useful CLI Patterns

# Query with JMESPath
aws lambda list-functions --query 'Functions[].FunctionName' --output text

# Wait for resource to be ready
aws cloudformation wait stack-create-complete --stack-name my-stack

# Dry run (check permissions without executing)
aws ec2 run-instances --dry-run --image-id ami-123 --instance-type t3.micro

AWS CLI Pagination

# Giới hạn số items per API call (tránh timeout)
aws s3api list-objects-v2 --bucket my-bucket --page-size 100

# Giới hạn tổng số items trả về
aws s3api list-objects-v2 --bucket my-bucket --max-items 50

# Tiếp tục từ page trước
aws s3api list-objects-v2 --bucket my-bucket --starting-token eyJ...

Signing Requests (SigV4)

  • Tất cả AWS API requests phải được signed bằng Signature Version 4
  • SDK tự động handle signing
  • Manual signing cần thiết khi gọi API trực tiếp (HTTP)

Exponential Backoff

Attempt 1: wait 1s
Attempt 2: wait 2s
Attempt 3: wait 4s
Attempt 4: wait 8s
Attempt 5: wait 16s (+ random jitter)
  • Đã built-in trong AWS SDK
  • Jitter giúp tránh thundering herd problem
  • Chỉ retry cho 5xx errors và throttling, KHÔNG retry 4xx (trừ throttling)

Exam Tip: Credential chain order là câu hỏi phổ biến. Luôn dùng IAM Roles (Instance Profile / Task Role / Execution Role) thay vì hardcode credentials. Exponential backoff đã có sẵn trong SDK.