SDK tìm credentials theo thứ tự ưu tiên:
| Priority | Source | Mô tả |
|---|---|---|
| 1 | Code (hardcoded) | KHÔNG BAO GIỜ dùng trong production |
| 2 | Environment Variables | AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN |
| 3 | Shared Credentials File | ~/.aws/credentials (profiles) |
| 4 | AWS Config File | ~/.aws/config |
| 5 | Container Credentials | ECS Task Role |
| 6 | Instance Profile | EC2 Instance Profile / Lambda Execution Role |
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
| Mode | Mô tả |
|---|---|
| Legacy | Retry cơ bản, không backoff |
| Standard | Exponential backoff + jitter |
| Adaptive | Standard + client-side rate limiting |
AWS CLI là unified tool để quản lý AWS services từ command line.
| Feature | Mô tả |
|---|---|
| Profiles | Multiple accounts/roles (--profile prod) |
| Output formats | JSON, YAML, text, table (--output json) |
| Query | JMESPath filtering (--query 'Items[].id.S') |
| Pagination | --page-size, --max-items, --starting-token |
| Dry run | --dry-run cho EC2 operations |
| Wait | aws ... wait cho async operations |
# 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
# 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
# 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...
Attempt 1: wait 1s
Attempt 2: wait 2s
Attempt 3: wait 4s
Attempt 4: wait 8s
Attempt 5: wait 16s (+ random jitter)
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.