☁️ AWS Fundamentals
🎯 What is AWS?
Amazon Web Services (AWS) is a comprehensive cloud computing platform offering over 200 services including compute, storage, databases, networking, and machine learning. It is the largest cloud provider globally.
Key concept: AWS follows a pay-as-you-go model with global infrastructure spanning regions and availability zones.
Deep Explanation
AWS revolutionized IT infrastructure by making enterprise-grade computing accessible to everyone. It provides on-demand resources that scale automatically.
Why it matters: AWS powers millions of businesses from startups to enterprises, offering reliability, security, and global reach.
# AWS SDK (boto3) example
import boto3
# Create EC2 client
ec2 = boto3.client('ec2', region_name='us-east-1')
# Describe instances
response = ec2.describe_instances()
for reservation in response['Reservations']:
for instance in reservation['Instances']:
print(f"Instance: {instance['InstanceId']}")
print(f"State: {instance['State']['Name']}")
print(f"Type: {instance['InstanceType']}")
# Create S3 bucket
s3 = boto3.client('s3')
s3.create_bucket(Bucket='my-bucket', CreateBucketConfiguration={
'LocationConstraint': 'us-west-2'
})
# Upload file
s3.upload_file('local_file.txt', 'my-bucket', 'remote_file.txt')🖥️ EC2 Compute
🎯 Elastic Compute Cloud
Amazon EC2 provides virtual servers in the cloud. It offers scalable compute capacity with various instance types for different workloads.
EC2 Features
Instance types: General purpose, compute optimized, memory optimized, storage optimized, GPU. Purchasing options: On-demand, Reserved, Spot, Savings Plans. EBS: Elastic Block Store for persistent storage.
Auto Scaling: Automatically adjust capacity. Load Balancer: Distribute traffic.
# Launch EC2 instance
import boto3
ec2 = boto3.resource('ec2')
# Create instance
instances = ec2.create_instances(
ImageId='ami-0c55b159cbfafe1f0',
MinCount=1,
MaxCount=1,
InstanceType='t2.micro',
KeyName='my-keypair',
SecurityGroupIds=['sg-12345678'],
SubnetId='subnet-12345678',
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': 'MyServer'}]
}]
)
instance = instances[0]
print(f"Instance ID: {instance.id}")
print(f"Public IP: {instance.public_ip_address}")
# Stop/Start instance
instance.stop()
instance.wait_until_stopped()
instance.start()
instance.wait_until_running()
# Terminate instance
instance.terminate()📁 S3 Storage
🎯 Simple Storage Service
Amazon S3 is a highly durable, scalable object storage service. It stores data as objects in buckets with 99.999999999% durability.
S3 Features
Storage classes: Standard, Intelligent-Tiering, Infrequent Access, Glacier, Deep Archive. Versioning: Keep multiple versions of objects. Encryption: Server-side and client-side encryption.
Lifecycle policies: Automate transitions between storage classes.
# S3 operations
import boto3
s3 = boto3.client('s3')
bucket_name = 'my-bucket'
# List buckets
buckets = s3.list_buckets()
for bucket in buckets['Buckets']:
print(f"Bucket: {bucket['Name']}")
# Upload with encryption
s3.put_object(
Bucket=bucket_name,
Key='file.txt',
Body=b'Hello World',
ServerSideEncryption='AES256',
StorageClass='STANDARD_IA',
Metadata={'author': 'user'}
)
# Download with versioning
s3.download_file(bucket_name, 'file.txt', 'local_file.txt')
# Generate presigned URL
url = s3.generate_presigned_url(
'get_object',
Params={'Bucket': bucket_name, 'Key': 'file.txt'},
ExpiresIn=3600
)
print(f"Presigned URL: {url}")
# Lifecycle configuration
lifecycle = {
'Rules': [{
'ID': 'Archive Rule',
'Status': 'Enabled',
'Prefix': 'logs/',
'Transitions': [{
'Days': 30,
'StorageClass': 'GLACIER'
}]
}]
}
s3.put_bucket_lifecycle_configuration(
Bucket=bucket_name,
LifecycleConfiguration=lifecycle
)🗄️ RDS Databases
🎯 Relational Database Service
Amazon RDS provides managed relational databases with automatic backups, patching, and scaling. Supports MySQL, PostgreSQL, Oracle, SQL Server, MariaDB.
RDS Features
Multi-AZ: Automatic failover to standby. Read replicas: Scale read traffic. Backups: Automated snapshots and point-in-time recovery. Performance Insights: Monitor database performance.
Aurora: AWS's high-performance MySQL/PostgreSQL compatible database.
# RDS operations
import boto3
rds = boto3.client('rds')
# Create DB instance
response = rds.create_db_instance(
DBInstanceIdentifier='mydb',
Engine='postgres',
EngineVersion='13.4',
DBInstanceClass='db.t3.micro',
AllocatedStorage=20,
MasterUsername='admin',
MasterUserPassword='password123',
MultiAZ=True,
BackupRetentionPeriod=7,
PubliclyAccessible=False,
StorageEncrypted=True,
Tags=[{'Key': 'Environment', 'Value': 'Production'}]
)
# Create read replica
rds.create_db_instance_read_replica(
DBInstanceIdentifier='mydb-read-replica',
SourceDBInstanceIdentifier='mydb',
DBInstanceClass='db.t3.micro',
AvailabilityZone='us-east-1b'
)
# Create snapshot
rds.create_db_snapshot(
DBInstanceIdentifier='mydb',
DBSnapshotIdentifier='mydb-snapshot-2024'
)
# Restore from snapshot
rds.restore_db_instance_from_db_snapshot(
DBInstanceIdentifier='mydb-restored',
DBSnapshotIdentifier='mydb-snapshot-2024',
DBInstanceClass='db.t3.micro'
)⚡ Lambda Serverless
🎯 Serverless Computing
AWS Lambda runs code in response to events without provisioning servers. You pay only for compute time used.
Lambda Features
Event sources: S3, DynamoDB, API Gateway, SQS, CloudWatch. Runtimes: Node.js, Python, Java, Go, .NET, Ruby. Concurrency: 1000 concurrent executions (default).
Duration: Up to 15 minutes. Memory: 128MB to 10GB.
# Lambda function (Python)
import json
import boto3
def lambda_handler(event, context):
"""
AWS Lambda function handler
"""
# Get input
name = event.get('name', 'World')
# Process
response = {
'statusCode': 200,
'body': json.dumps({
'message': f'Hello, {name}!',
'event': event
})
}
# If S3 event triggered
if 'Records' in event:
for record in event['Records']:
if record['eventSource'] == 'aws:s3':
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
print(f"Object uploaded: {bucket}/{key}")
process_s3_object(bucket, key)
return response
def process_s3_object(bucket, key):
"""Process S3 object"""
s3 = boto3.client('s3')
response = s3.get_object(Bucket=bucket, Key=key)
data = response['Body'].read()
print(f"Processing {len(data)} bytes")
# Deploy Lambda
def deploy_lambda():
lambda_client = boto3.client('lambda')
with open('function.zip', 'rb') as f:
zip_data = f.read()
response = lambda_client.create_function(
FunctionName='my-function',
Runtime='python3.9',
Role='arn:aws:iam::123456789012:role/lambda-execution-role',
Handler='handler.lambda_handler',
Code={'ZipFile': zip_data},
MemorySize=512,
Timeout=30,
Environment={'Variables': {'ENV': 'production'}}
)
print(f"Function ARN: {response['FunctionArn']}")🌐 VPC Networking
🎯 Virtual Private Cloud
Amazon VPC creates a logically isolated network in the AWS cloud. It provides full control over networking including IP addresses, subnets, and routing.
VPC Features
Subnets: Public (internet-facing) and private. Security Groups: Instance-level firewall. NACLs: Subnet-level firewall. VPC Peering: Connect VPCs. VPN/Connect: Connect to on-premise.
Direct Connect: Dedicated network connection.
# VPC operations
import boto3
ec2 = boto3.resource('ec2')
# Create VPC
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc.create_tags(Tags=[{'Key': 'Name', 'Value': 'MyVPC'}])
vpc.wait_until_available()
print(f"VPC ID: {vpc.id}")
# Create subnets
public_subnet = ec2.create_subnet(
VpcId=vpc.id,
CidrBlock='10.0.1.0/24',
AvailabilityZone='us-east-1a'
)
private_subnet = ec2.create_subnet(
VpcId=vpc.id,
CidrBlock='10.0.2.0/24',
AvailabilityZone='us-east-1a'
)
# Create Internet Gateway
igw = ec2.create_internet_gateway()
vpc.attach_internet_gateway(InternetGatewayId=igw.id)
# Create Route Table
route_table = ec2.create_route_table(VpcId=vpc.id)
route_table.create_route(
DestinationCidrBlock='0.0.0.0/0',
GatewayId=igw.id
)
route_table.associate_with_subnet(SubnetId=public_subnet.id)
# Create Security Group
sg = ec2.create_security_group(
GroupName='web-sg',
Description='Web security group',
VpcId=vpc.id
)
sg.authorize_ingress(
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 80,
'ToPort': 80,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
}]
)🔒 IAM Security
🎯 Identity and Access Management
AWS IAM provides fine-grained access control to AWS resources. It manages users, groups, roles, and policies.
IAM Features
Users: Individual identities with credentials. Groups: Collections of users. Roles: Temporary permissions for services. Policies: JSON documents defining permissions.
MFA: Multi-factor authentication. Federation: Integrate with external identity providers.
# IAM operations
import boto3
iam = boto3.client('iam')
# Create user
response = iam.create_user(UserName='developer')
print(f"User ARN: {response['User']['Arn']}")
# Create access key
response = iam.create_access_key(UserName='developer')
print(f"Access Key: {response['AccessKey']['AccessKeyId']}")
# Create group
iam.create_group(GroupName='developers')
# Add user to group
iam.add_user_to_group(GroupName='developers', UserName='developer')
# Create policy
policy_document = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": "*"
}]
}
response = iam.create_policy(
PolicyName='s3-readonly',
PolicyDocument=json.dumps(policy_document)
)
# Attach policy to group
iam.attach_group_policy(
GroupName='developers',
PolicyArn=response['Policy']['Arn']
)
# Create role for EC2
assume_role_policy = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}
iam.create_role(
RoleName='ec2-role',
AssumeRolePolicyDocument=json.dumps(assume_role_policy)
)🌍 Route 53 DNS
🎯 Domain Name System
Amazon Route 53 is a highly available, scalable DNS service. It provides domain registration, DNS routing, and health checking.
Route 53 Features
Routing policies: Simple, Weighted, Latency, Failover, Geolocation, Multivalue. Health checks: Monitor endpoint health. Domain registration: Register and manage domains.
Traffic flow: Advanced routing configurations.
# Route 53 operations
import boto3
route53 = boto3.client('route53')
# Create hosted zone
response = route53.create_hosted_zone(
Name='example.com',
CallerReference='unique-id-123',
HostedZoneConfig={'Comment': 'My domain'}
)
zone_id = response['HostedZone']['Id']
# Create DNS record
route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
'Changes': [{
'Action': 'CREATE',
'ResourceRecordSet': {
'Name': 'www.example.com',
'Type': 'A',
'AliasTarget': {
'HostedZoneId': 'Z2FDTNDATAQYW2', # CloudFront zone ID
'DNSName': 'd123.cloudfront.net',
'EvaluateTargetHealth': False
}
}
}, {
'Action': 'CREATE',
'ResourceRecordSet': {
'Name': 'app.example.com',
'Type': 'A',
'TTL': 300,
'ResourceRecords': [{'Value': '192.168.1.1'}]
}
}]
}
)
# Create health check
health_check = route53.create_health_check(
CallerReference='hc-unique',
HealthCheckConfig={
'Type': 'HTTP',
'ResourcePath': '/health',
'Port': 80,
'RequestInterval': 30,
'FailureThreshold': 3
}
)
# Weighted routing policy
route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
'Changes': [{
'Action': 'CREATE',
'ResourceRecordSet': {
'Name': 'api.example.com',
'Type': 'A',
'SetIdentifier': 'us-east',
'Weight': 70,
'TTL': 60,
'ResourceRecords': [{'Value': '192.168.1.1'}]
}
}, {
'Action': 'CREATE',
'ResourceRecordSet': {
'Name': 'api.example.com',
'Type': 'A',
'SetIdentifier': 'us-west',
'Weight': 30,
'TTL': 60,
'ResourceRecords': [{'Value': '192.168.2.1'}]
}
}]
}
)🚀 CloudFront CDN
🎯 Content Delivery Network
Amazon CloudFront is a global CDN that delivers content with low latency and high transfer speeds via edge locations worldwide.
CloudFront Features
Edge locations: 400+ globally. Cache behavior: Customizable caching policies. Security: SSL/TLS, AWS WAF integration. Lambda@Edge: Run code at edge locations.
Invalidation: Remove cached content.
# CloudFront operations
import boto3
cloudfront = boto3.client('cloudfront')
# Create distribution
response = cloudfront.create_distribution(
DistributionConfig={
'CallerReference': 'unique-id',
'Enabled': True,
'Comment': 'My CDN distribution',
'Origins': {
'Quantity': 1,
'Items': [{
'Id': 's3-origin',
'DomainName': 'my-bucket.s3.amazonaws.com',
'S3OriginConfig': {
'OriginAccessIdentity': 'origin-access-identity/cloudfront/E123456'
}
}]
},
'DefaultCacheBehavior': {
'TargetOriginId': 's3-origin',
'ViewerProtocolPolicy': 'redirect-to-https',
'CachePolicyId': '658327ea-f89d-4fab-a63d-7e88639e58f6',
'Compress': True
},
'DefaultRootObject': 'index.html',
'Aliases': {
'Quantity': 2,
'Items': ['www.example.com', 'example.com']
},
'PriceClass': 'PriceClass_100'
}
)
print(f"Distribution ID: {response['Distribution']['Id']}")
print(f"Domain Name: {response['Distribution']['DomainName']}")
# Create invalidation
response = cloudfront.create_invalidation(
DistributionId='E123456',
InvalidationBatch={
'Paths': {
'Quantity': 2,
'Items': ['/image.jpg', '/styles/*']
},
'CallerReference': 'inv-123'
}
)
# Update cache policy
cloudfront.create_cache_policy(
CachePolicyConfig={
'Name': 'my-policy',
'DefaultTTL': 86400,
'MaxTTL': 31536000,
'MinTTL': 60,
'ParametersInCacheKeyAndForwardedToOrigin': {
'EnableAcceptEncodingGzip': True,
'EnableAcceptEncodingBrotli': True,
'HeadersConfig': {'HeaderBehavior': 'none'},
'CookiesConfig': {'CookieBehavior': 'none'},
'QueryStringsConfig': {'QueryStringBehavior': 'none'}
}
}
)📊 CloudWatch Monitoring
🎯 Observability Platform
Amazon CloudWatch provides monitoring and observability for AWS resources. It collects metrics, logs, and events for operational insight.
CloudWatch Features
Metrics: CPU, memory, disk, network. Alarms: Threshold-based notifications. Logs: Centralized log management. Dashboards: Custom monitoring views.
Container insights: Monitor ECS/EKS. Synthetics: Canary monitoring.
# CloudWatch operations
import boto3
cloudwatch = boto3.client('cloudwatch')
logs = boto3.client('logs')
# Put metric data
cloudwatch.put_metric_data(
Namespace='MyApplication',
MetricData=[
{
'MetricName': 'ResponseTime',
'Value': 125,
'Unit': 'Milliseconds',
'Dimensions': [{'Name': 'Endpoint', 'Value': '/api/v1'}]
},
{
'MetricName': 'ErrorCount',
'Value': 5,
'Unit': 'Count'
}
]
)
# Create alarm
cloudwatch.put_metric_alarm(
AlarmName='HighCPUAlarm',
AlarmDescription='Alert when CPU exceeds 80%',
ActionsEnabled=True,
OKActions=['arn:aws:sns:us-east-1:123456789012:my-topic'],
AlarmActions=['arn:aws:sns:us-east-1:123456789012:my-topic'],
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Statistic='Average',
Period=300,
EvaluationPeriods=2,
Threshold=80.0,
ComparisonOperator='GreaterThanThreshold'
)
# Create log group and stream
logs.create_log_group(logGroupName='/aws/lambda/my-function')
logs.create_log_stream(
logGroupName='/aws/lambda/my-function',
logStreamName='2024/01/01/[$LATEST]123456'
)
# Query logs
logs.start_query(
logGroupName='/aws/lambda/my-function',
startTime=int(time.time() - 3600),
endTime=int(time.time()),
queryString='fields @timestamp, @message | filter @message like /ERROR/'
)
# Create dashboard
cloudwatch.put_dashboard(
DashboardName='MyDashboard',
DashboardBody=json.dumps({
'widgets': [{
'type': 'metric',
'properties': {
'metrics': [['AWS/EC2', 'CPUUtilization', { 'stat': 'Average' }]],
'period': 300,
'stat': 'Average',
'region': 'us-east-1',
'title': 'EC2 CPU Utilization'
}
}]
})
)📊 DynamoDB
🎯 NoSQL Database
Amazon DynamoDB is a fully managed NoSQL database service that provides single-digit millisecond performance at any scale.
DynamoDB Features
Key-value: Primary key (partition key + sort key). GSI/LSI: Secondary indexes for alternate queries. Streams: Change data capture. DAX: In-memory cache.
On-demand/Provisioned: Flexible capacity modes.
# DynamoDB operations
import boto3
dynamodb = boto3.resource('dynamodb')
# Create table
table = dynamodb.create_table(
TableName='Users',
KeySchema=[
{'AttributeName': 'userId', 'KeyType': 'HASH'},
{'AttributeName': 'timestamp', 'KeyType': 'RANGE'}
],
AttributeDefinitions=[
{'AttributeName': 'userId', 'AttributeType': 'S'},
{'AttributeName': 'timestamp', 'AttributeType': 'N'},
{'AttributeName': 'email', 'AttributeType': 'S'}
],
GlobalSecondaryIndexes=[{
'IndexName': 'EmailIndex',
'KeySchema': [{'AttributeName': 'email', 'KeyType': 'HASH'}],
'Projection': {'ProjectionType': 'ALL'}
}],
ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
)
table.wait_until_exists()
# Put item
table.put_item(
Item={
'userId': 'user123',
'timestamp': 1704067200,
'name': 'Alice',
'email': 'alice@email.com',
'age': 30,
'preferences': {'theme': 'dark', 'notifications': True}
}
)
# Get item
response = table.get_item(Key={'userId': 'user123', 'timestamp': 1704067200})
item = response.get('Item')
print(item)
# Query items
response = table.query(
KeyConditionExpression='userId = :id',
ExpressionAttributeValues={':id': 'user123'}
)
items = response['Items']
# Update item
table.update_item(
Key={'userId': 'user123', 'timestamp': 1704067200},
UpdateExpression='SET age = :age, #n = :name',
ExpressionAttributeNames={'#n': 'name'},
ExpressionAttributeValues={':age': 31, ':name': 'Alice Updated'},
ReturnValues='UPDATED_NEW'
)
# Delete item
table.delete_item(Key={'userId': 'user123', 'timestamp': 1704067200})📨 SQS Messaging
🎯 Message Queues
Amazon SQS provides fully managed message queuing for decoupling application components. It offers two types: Standard (high throughput) and FIFO (ordered).
SQS Features
Reliability: Messages are stored redundantly. Visibility timeout: Prevent duplicate processing. Dead-letter queues: Handle failed messages. Delay queues: Defer message delivery.
Integration: SNS, Lambda, S3, EC2.
# SQS operations
import boto3
sqs = boto3.client('sqs')
# Create queue (Standard)
response = sqs.create_queue(
QueueName='my-queue',
Attributes={
'VisibilityTimeout': '30',
'MessageRetentionPeriod': '86400', # 24 hours
'MaximumMessageSize': '262144' # 256KB
}
)
queue_url = response['QueueUrl']
# Create FIFO queue
response = sqs.create_queue(
QueueName='my-queue.fifo',
Attributes={
'FifoQueue': 'true',
'ContentBasedDeduplication': 'true'
}
)
# Send message
response = sqs.send_message(
QueueUrl=queue_url,
MessageBody='Hello World',
DelaySeconds=5,
MessageAttributes={
'AttributeName': {
'DataType': 'String',
'StringValue': 'AttributeValue'
}
}
)
print(f"Message ID: {response['MessageId']}")
# Send batch
sqs.send_message_batch(
QueueUrl=queue_url,
Entries=[
{'Id': '1', 'MessageBody': 'Message 1'},
{'Id': '2', 'MessageBody': 'Message 2', 'DelaySeconds': 10}
]
)
# Receive and process messages
response = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
VisibilityTimeout=60
)
messages = response.get('Messages', [])
for message in messages:
print(f"Processing: {message['Body']}")
# Delete after processing
sqs.delete_message(
QueueUrl=queue_url,
ReceiptHandle=message['ReceiptHandle']
)
# Create dead-letter queue
dlq_response = sqs.create_queue(QueueName='dead-letter-queue')
dlq_url = dlq_response['QueueUrl']
dlq_arn = sqs.get_queue_attributes(
QueueUrl=dlq_url,
AttributeNames=['QueueArn']
)['Attributes']['QueueArn']
# Configure dead-letter queue
sqs.set_queue_attributes(
QueueUrl=queue_url,
Attributes={
'RedrivePolicy': json.dumps({
'deadLetterTargetArn': dlq_arn,
'maxReceiveCount': '3'
})
}
)🏛️ Architecture
🎯 Design Principles
AWS architecture follows Well-Architected Framework principles: Operational Excellence, Security, Reliability, Performance Efficiency, Cost Optimization, and Sustainability.
Best Practices
Design for failure: Multi-AZ, auto-scaling. Decouple: Use queues and event-driven patterns. Security: Least privilege, encryption. Monitoring: CloudWatch, X-Ray. Cost: Right-sizing, reserved instances.
Well-Architected Tool: Review and improve architecture.
# Architecture patterns
# Three-tier web application
# 1. Presentation layer (S3 + CloudFront)
# 2. Application layer (EC2 Auto Scaling + ALB)
# 3. Data layer (RDS + ElastiCache)
# Infrastructure as Code (CloudFormation)
template = {
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"WebServerSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "Enable HTTP access",
"SecurityGroupIngress": [{
"IpProtocol": "tcp",
"FromPort": "80",
"ToPort": "80",
"CidrIp": "0.0.0.0/0"
}]
}
},
"WebServer": {
"Type": "AWS::EC2::Instance",
"Properties": {
"InstanceType": "t2.micro",
"ImageId": "ami-0c55b159cbfafe1f0",
"SecurityGroupIds": [{"Ref": "WebServerSecurityGroup"}]
}
},
"AutoScalingGroup": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"MinSize": "1",
"MaxSize": "5",
"DesiredCapacity": "2",
"LaunchConfigurationName": {"Ref": "LaunchConfig"}
}
}
}
}
# Save template and deploy
with open('template.json', 'w') as f:
json.dump(template, f)🚀 Future
🎯 The Future of AWS
AWS continues to evolve with AI/ML, edge computing, quantum computing, and sustainability as key focus areas.
Emerging Trends
AI/ML: SageMaker, Bedrock, Q. Serverless: Lambda, EventBridge, Step Functions. Edge: Outposts, Local Zones, Wavelength. Quantum: Braket. Sustainability: Carbon footprint tools.
Data: Analytics, Warehousing, ML integration.
# Future services (conceptual)
# SageMaker - ML
import sagemaker
from sagemaker import get_execution_role
role = get_execution_role()
sagemaker.create_model(
ModelName='my-model',
PrimaryContainer={
'Image': '763104351884.dkr.ecr.us-east-1.amazonaws.com/pytorch-inference:1.13',
'ModelDataUrl': 's3://my-bucket/model.tar.gz'
},
ExecutionRoleArn=role
)
# EventBridge - Event-driven
eventbridge = boto3.client('events')
eventbridge.put_rule(
Name='my-rule',
EventPattern=json.dumps({
'source': ['aws.s3'],
'detail-type': ['Object Created']
})
)
# Bedrock - Generative AI
bedrock = boto3.client('bedrock-runtime')
response = bedrock.invoke_model(
modelId='anthropic.claude-v2',
body=json.dumps({
'prompt': 'What is AWS?',
'max_tokens_to_sample': 100
})
)
# Amazon Q - Code assistant
# Integrated with IDE for code completion and generation
# Sustainability
# AWS Customer Carbon Footprint Tool
# Track and reduce carbon emissions