Module 8: Public Cloud (AWS) — The Complete Guide
Goal
AWS is the largest cloud and the default in most job postings. You already know the concepts (networks, servers, containers, load balancing) — this module maps them to AWS services and adds the cloud-native pieces: IAM, regions/AZs, ECR, EC2, ECS, Lambda, ELB, and CloudFront.
1. Cloud Mental Model
Cloud = renting infrastructure by the second via an API. The killer feature isn't cost — it's programmability: aws ec2 run-instances gives you a server in 40 seconds; an API call deletes it. Infrastructure becomes software (which is why Terraform, Module 9, exists).
Service spectrum — the more managed, the less you operate:
IaaS ──────────────► PaaS/Containers ─────────► Serverless
EC2 (raw VMs) ECS/EKS (managed Lambda (just code,
you patch the OS orchestration) no servers visible)Rule of thumb in real teams: use the most managed option that fits; run raw EC2 only when you must.
Analogy
Think of the cloud as a serviced city you move into instead of a town you build yourself — nobody pours their own roads or digs their own wells. EC2 is an unfurnished apartment: the building is maintained for you, but you furnish and clean it. ECS is a serviced suite where housekeeping handles the rooms, and Lambda is a taxi — no lease at all, you just pay per ride.
2. Regions & Availability Zones
- Region — a geographic area (
us-east-1N. Virginia,eu-west-1Ireland,ap-southeast-1Singapore). Regions are isolated from each other; most resources live in exactly one. - Availability Zone (AZ) — one or more physically separate datacenters within a region (
us-east-1a,-1b,-1c), with independent power/network, connected by fast private links.
The design rule that follows: an AZ can fail (it happens!), so anything production runs in at least two AZs — which is exactly why the Module 4 VPC had subnets in AZ-a and AZ-b, and why a load balancer spans them. Region choice: latency to users, data-residency laws, price (regions differ), service availability.
Analogy
A region is a city, and its availability zones are separate districts, each with its own power grid and water supply. If one district blacks out, a shop with a branch in a second district keeps trading — which is exactly why production always rents space in at least two districts of the same city.
3. IAM — Identity & Access Management (Learn This First, Seriously)
Every AWS breach story starts with bad IAM. IAM answers: who can perform which actions on which resources.
Building blocks:
- User — a human (or legacy service) with long-lived credentials.
- Group — users bundled for shared permissions (
developers,admins). - Role — an identity that is assumed temporarily — by EC2 instances, Lambda, ECS tasks, or CI via OIDC. No stored keys. Prefer roles over users everywhere.
- Policy — a JSON document allowing/denying actions:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::myapp-uploads/*"
}]
}Evaluation logic: default deny → explicit Allow grants → explicit Deny always wins.
Non-negotiable practices:
- Root account: enable MFA, lock it away, never use it daily.
- Humans: individual users in groups, MFA enforced.
- Software: roles, never access keys pasted into servers or code. An EC2 app needing S3 gets an instance profile role — SDKs pick up temporary credentials automatically.
- Least privilege: grant
s3:GetObjecton one bucket, nots3:*on*. Start narrow, widen when errors demand it. - CI/CD: GitHub Actions assumes a role via OIDC — zero long-lived secrets in GitHub.
Real incident pattern you're preventing: developer commits an access key with AdministratorAccess to a public repo → bots find it in ~minutes → a $50k Bitcoin-mining bill by morning. Roles + least privilege + secret scanning make this impossible.
Analogy
IAM is the city's keycard system, and nobody carries a master key. Each keycard opens exactly the doors its holder needs and nothing more, every door defaults to locked until access is explicitly granted, and contractors get visitor badges that expire the same day instead of permanent keys — that expiring badge is a role.
4. ECR — Your Private Docker Registry
Elastic Container Registry stores images privately, integrated with IAM (access via policies, not passwords), with vulnerability scan-on-push and lifecycle policies (auto-delete untagged/old images so storage doesn't balloon).
aws ecr create-repository --repository-name myapp
aws ecr get-login-password --region us-east-1 \
| docker login --username AWS --password-stdin 123456789.dkr.ecr.us-east-1.amazonaws.com
docker tag myapp:v2.3.1 123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:v2.3.1
docker push 123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:v2.3.1Analogy
ECR is your own keycard-access warehouse in the serviced city, holding the sealed shipping crates (images) your services deploy. The city's keycard system (IAM) decides who may deposit or withdraw a crate — there's no separate warehouse password — an inspector x-rays every crate the moment it arrives (scan-on-push), and the warehouse auto-clears crates past their date so you never pay rent on forgotten stock.
In CI, the aws-actions/amazon-ecr-login action + an OIDC role replaces the manual login. ECS/EKS pull from ECR using their task/node roles — credentials never appear anywhere.
5. EC2 — Virtual Machines
Analogy
An EC2 instance is the unfurnished apartment of the serviced city: you pick the floor plan (instance type) and the fittings it comes with (AMI), and everything inside the walls — cleaning, repairs, locking the door — is on you. The user-data script is the checklist the movers execute the day you get the keys.
Launching an instance = choosing:
- AMI (Amazon Machine Image) — the OS snapshot (Ubuntu 24.04, Amazon Linux 2023).
- Instance type —
t3.micro(free tier, burstable),m6i.large(general),c7g.xlarge(compute, ARM/Graviton — cheaper per perf; remember multi-platform images from Module 5!). Letter = family, number = generation, size = resources. - Key pair — SSH public key injected at boot.
- Security Group — the instance firewall (below).
- VPC/subnet — your Module 4 network design.
- EBS volume — network-attached persistent disk (survives stop/start; gp3 is the default choice).
- User data — a boot script; pair with your bash skills:
#!/bin/bash
apt-get update && apt-get install -y docker.io
systemctl enable --now docker
docker run -d --restart unless-stopped -p 80:8080 \
123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:v2.3.1Security Groups (SGs) = stateful virtual firewalls. The pro pattern from Module 4, expressed natively: rules reference other SGs:
alb-sg: inbound 443 from 0.0.0.0/0
app-sg: inbound 8080 from alb-sg ← only the ALB, by identity not IP
db-sg: inbound 5432 from app-sg ← only app instancesInstances change IPs; SG references never break. (NACLs are the stateless subnet-level layer — mostly left at defaults.)
Analogy
A security group rule that references another security group is a doorman working from a guest list of people, not street addresses. The rule says admit anyone from the reception desk, so even when receptionists change shifts or the desk moves, the doorman still recognizes them — the list never goes stale.
Pricing awareness (interviews love this): On-Demand (default) → Reserved/Savings Plans (~40–60% off for 1–3yr commitment, steady workloads) → Spot (up to ~90% off, can be reclaimed with 2-min warning — perfect for CI runners and batch jobs, never for your only database).
6. Lambda — Serverless Functions
Upload code (or a container image); AWS runs it per event, scaling from 0 to thousands of concurrent executions; you pay per millisecond. No servers to patch, ever.
def handler(event, context):
# event = the trigger payload (S3 upload info, API request, SQS message...)
return {"statusCode": 200, "body": "processed"}Triggers: API Gateway (HTTP APIs), S3 events (file uploaded → process it), SQS (queue worker), EventBridge cron (rate(1 hour) — serverless cron jobs!), DynamoDB streams.
Real DevOps uses: image thumbnailer on S3 upload; nightly cleanup jobs; Slack alert webhooks; glue between services. Limits to respect: 15-min max runtime, memory 128MB–10GB, and cold starts (first invocation after idle adds latency) — so it's ideal for spiky/event work, not always for latency-critical hot paths. Rule of thumb: request/event-driven and short → Lambda; long-running service → containers.
Analogy
Lambda is the city's taxi service: you do not own a car, insure it, or park it — you hail a ride only when an event turns up, and you pay by the metered second. The catch is the cold start: if no cab is idling nearby, the first pickup after a quiet spell takes a little longer to arrive.
7. ECS — Managed Container Orchestration
ECS is AWS's simpler alternative to Kubernetes. Concepts map cleanly:
| ECS | ≈ Kubernetes |
|---|---|
| Task definition | Pod spec |
| Task | Pod |
| Service | Deployment + Service |
| Cluster | Cluster |
Two launch types: EC2 (you manage the instances) and Fargate (serverless — you specify CPU/memory per task, AWS finds the compute; no nodes to patch). Fargate is the default choice for most teams.
Analogy
The EC2 launch type is renting the whole apartment building and assigning tenants to rooms yourself — and fixing the elevators too. Fargate is a serviced hotel: you state how big a room each guest needs, and the hotel finds the space, cleans it, and patches the plumbing without you ever seeing a corridor.
A highly-available containerized service on ECS:
- Task definition: image (from ECR), 0.5 vCPU / 1GB, port 8080, env vars from SSM Parameter Store/Secrets Manager, an IAM task role (the container's own least-privilege identity).
- Service: desired count 3, spread across two AZs' private subnets, attached to an ALB target group with health checks.
- Deploy = register new task definition revision with the new image tag → ECS rolls tasks gradually, health-checked (rolling update, zero downtime). CI does this with
aws ecs update-service. - Auto scaling on CPU/request-count per target.
ECS vs EKS (real decision): ECS = simpler, cheaper, deeply AWS-integrated — great when you're all-in on AWS. EKS = real Kubernetes — portability, the huge ecosystem (Helm, operators), industry-standard skills. Both are correct answers with reasons; knowing the trade-off is the senior signal.
8. ELB — Elastic Load Balancing
Managed load balancers spanning multiple AZs, health-checking targets, scaling themselves. Two that matter:
- ALB (Application Load Balancer) — Layer 7: understands HTTP. Routes by host/path (
/api/*→ api target group), terminates TLS (free auto-renewing certs via ACM), supports WebSockets, integrates with ECS/EKS. Your default for web apps. - NLB (Network Load Balancer) — Layer 4: forwards TCP/UDP at extreme scale with static IPs. For non-HTTP protocols (databases, MQTT, game servers) or when clients need fixed IPs to allowlist.
(Layer 4 vs 7 = the OSI table from Module 4 paying rent.)
ALB anatomy: Listener (443) → Rules (path/host matching) → Target Groups (instances/ECS tasks/Lambdas) each with a health check (/health, 200 expected). Unhealthy target → traffic stops flowing to it → that's your zero-downtime deploy and your automatic failure isolation.
Analogy
A load balancer is the receptionist in the lobby of a building full of identical offices. Every visitor states their business (the path), the receptionist directs them to an office that is open and answering its phone, and when one office goes quiet, visitors are steered elsewhere until it picks up again.
9. CloudFront — CDN
CloudFront caches content at 400+ global edge locations, so a user in Singapore gets your static assets from Singapore, not Virginia.
Analogy
CloudFront is a chain of corner shops stocking copies of goods from one distant central warehouse. Locals buy from the shop down the street instead of waiting for cross-country shipping, shops restock only when an item is missing or past its date, and printing a new label on every product batch (fingerprinted filenames) means stale stock simply never gets asked for.
- Origin — where content truly lives (S3 bucket, ALB).
- Distribution — the CDN config; you get
d1234.cloudfront.net, put your domain on it via DNS. - Cache behaviors — per-path TTLs:
/static/*cache 1 year;/api/*no cache (pass-through — still gains TLS termination close to users and DDoS absorption). - Invalidation — purge after deploys (
aws cloudfront create-invalidation --paths "/*"), or better: fingerprinted filenames (app.9f3b2c.js) cached forever, so no invalidation needed.
Classic architecture: S3 (private, accessed via OAC) + CloudFront for the frontend; ALB + ECS for the API — cheap, fast, and the S3 bucket is never publicly exposed.
10. The Reference Architecture (Tie It All Together)
S3 stays private, accessed via OAC
ALB in 2+ AZs with ACM TLS, path rules
3 tasks, private subnets, app-sg, task role
Multi-AZ, db-sg, private subnet, no internet route
Around the request path:
- CI/CD: GitHub Actions → OIDC role → push to ECR →
aws ecs update-service - Secrets: SSM Parameter Store / Secrets Manager (injected into tasks)
- Monitoring: CloudWatch logs/metrics/alarms (Module 10 expands this)
- Cost guardrail: AWS Budgets alert at 50/80/100% of expected spend
Every box maps to a module you've completed. That's the point — AWS is your existing knowledge with an API in front of it.
Free-tier discipline: set a billing alarm on day one; prefer t3.micro/Fargate-minimal; delete NAT Gateways when done (~$32/month idle — the classic surprise bill); terminate everything after each lab (Terraform, next module, makes this one command).
Analogy
The cloud bill is a utility meter that never sleeps: it keeps spinning for every idle NAT Gateway and forgotten instance, whether or not anyone is home. A billing alarm on day one is the smart meter that texts you long before the shocking envelope lands in the mailbox.
11. Hands-On Project (Do This)
- IAM foundations: MFA on root, admin group + your user, and an OIDC role for GitHub Actions scoped to ECR push + ECS deploy.
- Create an ECR repo with scan-on-push; adapt your Module 6 pipeline to push there via OIDC (no stored AWS keys!).
- EC2 warm-up: launch
t3.microin your Module 4 VPC's public subnet, user-data script that runs your container, SG allowing 80 from your IP only. Verify, then terminate. - The real deployment: ALB (2 public subnets) → ECS Fargate service (2 tasks, private subnets) pulling from ECR, ALB health checks on
/health, DB password from Secrets Manager. - Wire CI/CD: merge to main → build → push ECR →
aws ecs update-service --force-new-deployment; watch the rolling replacement in the console. - Break & heal: kill a task manually — watch ECS replace it and the ALB route around it. Deploy an image whose health check fails — watch the deployment circuit-breaker roll back.
- Lambda: S3 bucket + Lambda triggered on upload that logs object metadata; add an EventBridge cron Lambda that posts to Slack.
- CloudFront: host a static page in a private S3 bucket behind CloudFront with OAC.
- Tear everything down and confirm with the billing dashboard.
12. Self-Check Questions
- Region vs AZ — and why does production require two AZs?
- User vs role — why should an EC2 app never have access keys on disk?
- Write (from memory) a least-privilege policy for read-only access to one S3 bucket.
- ALB vs NLB — which for a Postgres endpoint? For a web app with
/apiand/routing? - Fargate vs EC2 launch type; ECS vs EKS — trade-offs?
- When is Lambda the wrong choice? What's a cold start?
- Your NAT Gateway question from Module 4: which subnets route through it here, and what does it cost you to forget it?
Next → Module 9: Infrastructure as Code (Terraform)
