AWS Services Cheatsheet

A comprehensive guide to Amazon Web Services (AWS) - covering essential services, CLI commands, and best practices

AWS Basics

AWS Global Infrastructure

Understanding AWS's global infrastructure components

# AWS Global Infrastructure Components
- Regions: Geographic areas (e.g., us-east-1, eu-west-1)
- Availability Zones (AZs): Isolated data centers within a region
- Edge Locations: CDN endpoints for CloudFront
- Local Zones: Extensions of regions closer to population centers
- Wavelength Zones: For ultra-low latency applications
- Outposts: AWS services on-premises

# Region Selection Factors
- Data residency requirements
- Latency to end users
- Available services (not all services available in all regions)
- Pricing (varies by region)

# AWS Top-Level Service Categories
- Compute
- Storage
- Database
- Networking & Content Delivery
- Security, Identity & Compliance
- Management & Governance
- Analytics
- Application Integration
- Machine Learning

AWS CLI Configuration

Setting up and using the AWS Command Line Interface

# Install AWS CLI
pip install awscli
# or
brew install awscli

# Configure AWS CLI
aws configure
# Enter: 
# - AWS Access Key ID
# - AWS Secret Access Key
# - Default region name (e.g., us-east-1)
# - Default output format (json, text, table)

# Configuration is stored in:
# ~/.aws/credentials
# ~/.aws/config

# List all S3 buckets
aws s3 ls

# Using profiles
aws configure --profile prod
aws s3 ls --profile prod

# Set environment variable for temporary profile use
export AWS_PROFILE=prod

# Using AWS CLI with MFA
aws sts get-session-token --serial-number arn:aws:iam::123456789012:mfa/user --token-code 123456

AWS Account Management

Managing AWS accounts and billing

# AWS Organizations
- Multi-account management
- Consolidated billing
- Service Control Policies (SCPs)

# Important management URLs
- AWS Console: https://console.aws.amazon.com/
- Billing Dashboard: https://console.aws.amazon.com/billing/
- Cost Explorer: https://console.aws.amazon.com/cost-management/
- AWS Organizations: https://console.aws.amazon.com/organizations/
- IAM: https://console.aws.amazon.com/iam/

# Cost Management
- Budgets: Set custom budgets and alerts
- Cost Explorer: Visualize and manage costs
- Cost Allocation Tags: Tag resources for cost tracking
- Trusted Advisor: Recommendations for cost optimization

# AWS Free Tier
- 12 months free: EC2, S3, RDS, etc.
- Always free: Lambda (1M requests/month), DynamoDB (25GB)
- Trials: Services with short-term free trials

Compute Services

EC2 (Elastic Compute Cloud)

Virtual servers in the cloud

# EC2 Instance Types
- General Purpose (T3, M5): Balanced CPU/memory
- Compute Optimized (C5): High CPU
- Memory Optimized (R5): High memory
- Storage Optimized (I3, D2): High I/O
- Accelerated Computing (P3, G4): GPUs

# EC2 Pricing Options
- On-Demand: Pay by the hour, no commitment
- Reserved Instances: 1 or 3 year commitment, up to 75% discount
- Spot Instances: Bid for unused capacity, up to 90% discount
- Savings Plans: 1 or 3 year commitment for consistent usage
- Dedicated Hosts: Physical servers dedicated to you

# Launch an EC2 instance (AWS CLI)
aws ec2 run-instances \
  --image-id ami-0abcdef1234567890 \
  --instance-type t2.micro \
  --key-name MyKeyPair \
  --security-group-ids sg-903004f8 \
  --subnet-id subnet-6e7f829e

# Connect to EC2 (SSH)
ssh -i "key.pem" ec2-user@ec2-198-51-100-1.compute-1.amazonaws.com

# Lifecycle Management
aws ec2 start-instances --instance-ids i-1234567890abcdef0
aws ec2 stop-instances --instance-ids i-1234567890abcdef0
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0

Lambda (Serverless)

Run code without provisioning servers

# Lambda Features
- Serverless compute service
- Supports Node.js, Python, Java, Go, Ruby, .NET Core
- Pay only for the compute time used
- Automatic scaling
- Integrates with many AWS services
- Maximum execution time: 15 minutes

# Lambda Execution Model
- Event-driven: Respond to events from AWS services
- API Gateway: HTTP endpoints trigger functions
- Scheduled: Run on a schedule using CloudWatch Events

# Create a Lambda function (AWS CLI)
aws lambda create-function \
  --function-name my-function \
  --runtime python3.9 \
  --role arn:aws:iam::123456789012:role/lambda-role \
  --handler lambda_function.handler \
  --zip-file fileb://function.zip

# Invoke a Lambda function
aws lambda invoke \
  --function-name my-function \
  --payload '{"key1": "value1", "key2": "value2"}' \
  response.json

# Lambda Environment Variables
aws lambda update-function-configuration \
  --function-name my-function \
  --environment "Variables={DB_HOST=db.example.com,DB_USER=admin}"

ECS (Elastic Container Service)

Run and manage Docker containers

# ECS Core Components
- Cluster: Logical grouping of tasks or services
- Task Definition: Blueprint for your application (like a Dockerfile)
- Task: Instance of a task definition running on a container instance
- Service: Maintains desired count of tasks
- Container Instance: EC2 instance running the ECS agent

# ECS Launch Types
- EC2: Manage your own EC2 instances
- Fargate: Serverless container platform, no EC2 management

# Create an ECS cluster
aws ecs create-cluster --cluster-name my-cluster

# Register a task definition
aws ecs register-task-definition \
  --cli-input-json file://task-definition.json

# Run a task
aws ecs run-task \
  --cluster my-cluster \
  --task-definition my-task:1 \
  --count 1 \
  --launch-type FARGATE \
  --network-configuration "awsvpcConfiguration={subnets=[subnet-abcd1234],securityGroups=[sg-abcd1234],assignPublicIp=ENABLED}"

# Create a service
aws ecs create-service \
  --cluster my-cluster \
  --service-name my-service \
  --task-definition my-task:1 \
  --desired-count 2 \
  --launch-type FARGATE

Storage Services

S3 (Simple Storage Service)

Object storage for files and data

# S3 Storage Classes
- Standard: General-purpose storage (99.99% availability)
- Intelligent-Tiering: Automatic cost optimization
- Standard-IA (Infrequent Access): Less frequently accessed data
- One Zone-IA: Lower cost for non-critical data
- Glacier: Long-term archival (retrieval time: minutes to hours)
- Glacier Deep Archive: Lowest cost, longest retrieval (12 hours)

# S3 CLI Commands
# Create a bucket
aws s3 mb s3://my-bucket

# Upload a file
aws s3 cp myfile.txt s3://my-bucket/

# Download a file
aws s3 cp s3://my-bucket/myfile.txt ./

# List bucket contents
aws s3 ls s3://my-bucket/

# Remove a file
aws s3 rm s3://my-bucket/myfile.txt

# Sync local directory with S3
aws s3 sync ./local-dir s3://my-bucket/target-dir

# S3 URL Formats
# Path-style (legacy)
https://s3.amazonaws.com/bucket-name/key-name

# Virtual-hosted style (preferred)
https://bucket-name.s3.amazonaws.com/key-name

# Website endpoint
http://bucket-name.s3-website-region.amazonaws.com/

EBS (Elastic Block Store)

Block storage for EC2 instances

# EBS Volume Types
- General Purpose SSD (gp2/gp3): Balance of price and performance
- Provisioned IOPS SSD (io1/io2): High-performance, mission-critical workloads
- Throughput Optimized HDD (st1): Big data, log processing
- Cold HDD (sc1): Lowest cost for infrequently accessed data
- Magnetic (standard): Legacy, previous generation

# Create an EBS volume
aws ec2 create-volume \
  --availability-zone us-east-1a \
  --size 8 \
  --volume-type gp3

# Attach a volume to an instance
aws ec2 attach-volume \
  --volume-id vol-1234567890abcdef0 \
  --instance-id i-1234567890abcdef0 \
  --device /dev/sdf

# Create a snapshot
aws ec2 create-snapshot \
  --volume-id vol-1234567890abcdef0 \
  --description "My snapshot"

# Create a volume from a snapshot
aws ec2 create-volume \
  --availability-zone us-east-1a \
  --snapshot-id snap-1234567890abcdef0

# Volume encryption (at rest)
aws ec2 create-volume \
  --availability-zone us-east-1a \
  --size 8 \
  --volume-type gp3 \
  --encrypted \
  --kms-key-id alias/aws/ebs

EFS (Elastic File System)

Fully managed file system for EC2

# EFS Features
- Elastic: Automatically scales as you add/remove files
- Shared: Multiple EC2 instances can access the same EFS
- Fully managed NFS file system
- Pay only for storage used
- Performance modes: General Purpose and Max I/O
- Throughput modes: Bursting and Provisioned

# Create an EFS file system
aws efs create-file-system \
  --performance-mode generalPurpose \
  --throughput-mode bursting \
  --encrypted \
  --tags Key=Name,Value=MyFileSystem

# Create a mount target
aws efs create-mount-target \
  --file-system-id fs-01234567 \
  --subnet-id subnet-abcd1234 \
  --security-groups sg-1234abcd

# Mount on EC2 (Linux)
sudo mkdir /mnt/efs
sudo mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport fs-01234567.efs.us-east-1.amazonaws.com:/ /mnt/efs

# Add to /etc/fstab for persistent mount
fs-01234567.efs.us-east-1.amazonaws.com:/ /mnt/efs nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport 0 0

Database Services

RDS (Relational Database Service)

Managed relational databases

# Supported Database Engines
- Amazon Aurora (MySQL/PostgreSQL compatible)
- MySQL
- PostgreSQL
- MariaDB
- Oracle
- SQL Server

# Create an RDS instance
aws rds create-db-instance \
  --db-instance-identifier mydb \
  --engine mysql \
  --master-username admin \
  --master-user-password secretpassword \
  --allocated-storage 20 \
  --db-instance-class db.t3.micro

# Create a read replica
aws rds create-db-instance-read-replica \
  --db-instance-identifier mydb-replica \
  --source-db-instance-identifier mydb

# Create a snapshot
aws rds create-db-snapshot \
  --db-instance-identifier mydb \
  --db-snapshot-identifier mydb-snapshot

# Restore from snapshot
aws rds restore-db-instance-from-db-snapshot \
  --db-instance-identifier mynewdb \
  --db-snapshot-identifier mydb-snapshot

# RDS Multi-AZ Deployment
aws rds modify-db-instance \
  --db-instance-identifier mydb \
  --multi-az \
  --apply-immediately

DynamoDB (NoSQL)

Fully managed NoSQL database service

# DynamoDB Core Concepts
- Tables: Collection of items
- Items: Group of attributes (similar to rows)
- Attributes: Fundamental data elements
- Primary Key: Uniquely identifies each item
  - Partition Key: Simple primary key
  - Partition Key + Sort Key: Composite primary key
- Secondary Indexes:
  - Global Secondary Index (GSI): Different partition key
  - Local Secondary Index (LSI): Same partition key, different sort key

# Create a table
aws dynamodb create-table \
  --table-name Music \
  --attribute-definitions \
      AttributeName=Artist,AttributeType=S \
      AttributeName=SongTitle,AttributeType=S \
  --key-schema \
      AttributeName=Artist,KeyType=HASH \
      AttributeName=SongTitle,KeyType=RANGE \
  --provisioned-throughput \
      ReadCapacityUnits=5,WriteCapacityUnits=5

# Write an item
aws dynamodb put-item \
  --table-name Music \
  --item \
      '{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}, "AlbumTitle": {"S": "Somewhat Famous"}, "Year": {"N": "2015"}}'

# Read an item
aws dynamodb get-item \
  --table-name Music \
  --key '{"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}}'

# Query items
aws dynamodb query \
  --table-name Music \
  --key-condition-expression "Artist = :artist" \
  --expression-attribute-values '{":artist": {"S": "No One You Know"}}'

# DynamoDB Streams
aws dynamodb update-table \
  --table-name Music \
  --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES

ElastiCache

In-memory caching service

# ElastiCache Engines
- Redis: Advanced data structures, persistence, replication
- Memcached: Simple, multi-threaded, scalable

# Create a Redis cluster
aws elasticache create-cache-cluster \
  --cache-cluster-id my-redis \
  --engine redis \
  --cache-node-type cache.t3.micro \
  --num-cache-nodes 1

# Create a Redis replication group
aws elasticache create-replication-group \
  --replication-group-id my-redis-group \
  --replication-group-description "My Redis Group" \
  --num-cache-clusters 3 \
  --cache-node-type cache.t3.micro \
  --engine redis

# Create a Memcached cluster
aws elasticache create-cache-cluster \
  --cache-cluster-id my-memcached \
  --engine memcached \
  --cache-node-type cache.t3.micro \
  --num-cache-nodes 2

# Describe cache clusters
aws elasticache describe-cache-clusters

# Common ElastiCache Use Cases
- Database query result caching
- Session storage
- Real-time analytics
- Leaderboards/Counting
- Message queuing
- Pub/Sub systems (Redis)

Networking & Content Delivery

VPC (Virtual Private Cloud)

Isolated cloud resources in a private network

# VPC Core Components
- VPC: Logical isolated network (172.16.0.0/16)
- Subnet: Range of IP addresses in a VPC (public or private)
- Route Table: Rules for network traffic direction
- Internet Gateway: Connect VPC to internet (for public subnets)
- NAT Gateway: Allow private subnets to access internet
- Security Group: Virtual firewall for instances (stateful)
- Network ACL: Subnet-level firewall (stateless)
- VPC Peering: Connect two VPCs

# Create a VPC
aws ec2 create-vpc --cidr-block 10.0.0.0/16 --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=MyVPC}]'

# Create a subnet
aws ec2 create-subnet \
  --vpc-id vpc-01234567890abcdef \
  --cidr-block 10.0.1.0/24 \
  --availability-zone us-east-1a \
  --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=Public1}]'

# Create an internet gateway
aws ec2 create-internet-gateway --tag-specifications 'ResourceType=internet-gateway,Tags=[{Key=Name,Value=MyIGW}]'

# Attach internet gateway to VPC
aws ec2 attach-internet-gateway --vpc-id vpc-01234567890abcdef --internet-gateway-id igw-01234567890abcdef

# Create a route table
aws ec2 create-route-table --vpc-id vpc-01234567890abcdef

# Create a route to the internet
aws ec2 create-route \
  --route-table-id rtb-01234567890abcdef \
  --destination-cidr-block 0.0.0.0/0 \
  --gateway-id igw-01234567890abcdef

# Associate route table with subnet
aws ec2 associate-route-table \
  --route-table-id rtb-01234567890abcdef \
  --subnet-id subnet-01234567890abcdef

Route 53 (DNS)

Scalable domain name system (DNS) service

# Route 53 Record Types
- A: Maps domain to IPv4 address
- AAAA: Maps domain to IPv6 address
- CNAME: Maps domain to another domain
- MX: Mail exchange record
- TXT: Text record (often for verification)
- NS: Name server records
- SOA: Start of authority

# Routing Policies
- Simple: Standard DNS routing
- Weighted: Route based on assigned weights
- Latency: Route to lowest latency region
- Failover: Active-passive failover
- Geolocation: Route based on user location
- Multivalue Answer: Return multiple values (like load balancing)
- Geoproximity: Route based on geographic location and bias

# Create a hosted zone
aws route53 create-hosted-zone \
  --name example.com \
  --caller-reference 2014-04-01-18:47 \
  --hosted-zone-config Comment="Hosted zone for example.com"

# Create a record set
aws route53 change-resource-record-sets \
  --hosted-zone-id Z1PA6795UKMFR9 \
  --change-batch '{
    "Changes": [
      {
        "Action": "CREATE",
        "ResourceRecordSet": {
          "Name": "www.example.com",
          "Type": "A",
          "TTL": 300,
          "ResourceRecords": [
            {
              "Value": "192.0.2.44"
            }
          ]
        }
      }
    ]
  }'

CloudFront (CDN)

Global content delivery network

# CloudFront Components
- Distribution: The main CDN configuration
- Origin: Where CloudFront gets your content (S3, EC2, ELB, etc.)
- Edge Location: Where content is cached
- TTL (Time to Live): How long content stays cached

# Distribution Types
- Web Distribution: Websites, APIs, media files
- RTMP Distribution: Streaming media files

# Create a distribution (from S3 bucket)
aws cloudfront create-distribution \
  --origin-domain-name mybucket.s3.amazonaws.com \
  --default-root-object index.html

# Security Features
- Origin Access Identity (OAI): Restrict S3 access to CloudFront
- WAF Integration: Web Application Firewall rules
- HTTPS: SSL/TLS encryption
- Field-level encryption: Encrypt specific data fields
- Signed URLs/Cookies: Restrict access to content

# Invalidate content (clear cache)
aws cloudfront create-invalidation \
  --distribution-id EDFDVBD6EXAMPLE \
  --paths "/images/*" "/index.html"

# Common Use Cases
- Static website hosting
- Dynamic content
- API acceleration
- Video streaming
- Software distribution

API Gateway

Create, publish, and manage APIs

# API Types
- REST API: Standard RESTful API
- HTTP API: Lower latency, lower cost, simpler
- WebSocket API: Two-way communication

# API Gateway Features
- Authentication: IAM, Cognito, Lambda Authorizers
- API Keys: For client identification and throttling
- Throttling: Limit request rates
- Caching: Reduce backend calls
- CORS support: Cross-origin resource sharing
- Request/Response transformations
- SDK Generation: Generate client SDKs

# Create a REST API
aws apigateway create-rest-api --name 'My API' --description 'My REST API'

# Create a resource (endpoint)
aws apigateway create-resource \
  --rest-api-id abcdef123 \
  --parent-id root-resource-id \
  --path-part "users"

# Create a method (HTTP verb)
aws apigateway put-method \
  --rest-api-id abcdef123 \
  --resource-id resource-id \
  --http-method GET \
  --authorization-type "NONE"

# Set up integration with Lambda
aws apigateway put-integration \
  --rest-api-id abcdef123 \
  --resource-id resource-id \
  --http-method GET \
  --type AWS_PROXY \
  --integration-http-method POST \
  --uri arn:aws:apigateway:region:lambda:path/2015-03-31/functions/arn:aws:lambda:region:account-id:function:function-name/invocations

# Deploy the API
aws apigateway create-deployment \
  --rest-api-id abcdef123 \
  --stage-name prod

ELB (Elastic Load Balancing)

Distribute traffic across multiple targets

# Load Balancer Types
- Application Load Balancer (ALB): HTTP/HTTPS, layer 7
- Network Load Balancer (NLB): TCP/UDP, layer 4, ultra-high performance
- Gateway Load Balancer (GWLB): For virtual appliances
- Classic Load Balancer (CLB): Legacy, basic HTTP/TCP

# Create an Application Load Balancer
aws elbv2 create-load-balancer \
  --name my-alb \
  --subnets subnet-abcdef01 subnet-abcdef02 \
  --security-groups sg-abcdef01

# Create a target group
aws elbv2 create-target-group \
  --name my-targets \
  --protocol HTTP \
  --port 80 \
  --vpc-id vpc-abcdef01 \
  --target-type instance

# Register targets
aws elbv2 register-targets \
  --target-group-arn arn:aws:elasticloadbalancing:region:account-id:targetgroup/my-targets/abcdefg \
  --targets Id=i-abcdef01 Id=i-abcdef02

# Create a listener
aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:region:account-id:loadbalancer/app/my-alb/abcdefg \
  --protocol HTTP \
  --port 80 \
  --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:region:account-id:targetgroup/my-targets/abcdefg

# ELB Features
- Health checks: Monitor instance health
- Sticky sessions: Route requests to the same instance
- SSL termination: Handle SSL at the load balancer
- Path-based routing (ALB): Route based on URL path
- Host-based routing (ALB): Route based on host header
- Integration with Auto Scaling