Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 70 ยท Practice, interviews and cheat sheet

Practice Exercises with Solutions

Practice AWS with hands-on exercises: write an IAM policy, design CIDR subnets, build S3 lifecycle rules, fix a Lambda handler, estimate costs and debug scenarios.

Reading about AWS is not the same as using it. This lesson gives you six exercises that mirror real work: writing a least-privilege policy, planning subnets, setting up storage tiers, writing a Lambda handler, estimating a bill and diagnosing failures. Each one has a short task, a runnable checker in your browser, and a solution you can compare against.

There is no AWS account behind this page, so the checkers are small Python stand-ins that test your answer against the rules of the real service (the policy evaluator, the standard ipaddress module, a lifecycle engine and so on). They are simpler than the real thing, and the prices in the cost exercise are invented round numbers, not current AWS prices. The skills transfer; the API calls shown in solutions are read-only.

How to work: each runnable example below contains a first attempt with a deliberate mistake, so you will see failing checks. Edit the code, press Run again, and keep going until everything passes. Try to fix it before reading the solution.

Exercise 1: write a least-privilege policy

Task. A reporting job runs under an IAM role. It must read objects under the reports/ prefix of the bucket acme-data, and it must be able to list that bucket. It must not read other prefixes, write, or delete anything.

Refresher: see Writing IAM Policies. Remember that s3:ListBucket applies to the bucket ARN, while s3:GetObject applies to object ARNs.

Python Exercise 1: fix the policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Solution. One check fails: listing the bucket. The second statement uses the object ARN pattern acme-data/*, which never matches the bucket ARN arn:aws:s3:::acme-data. Change that resource to the bucket ARN:

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::acme-data/reports/*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::acme-data",
      "Condition": { "StringLike": { "s3:prefix": ["reports/*"] } }
    }
  ]
}

The Condition is how real IAM limits listing to the reports/ prefix; the stand-in ignores conditions, which is why your fix passes with or without it. Note that nothing is allowed for PutObject and DeleteObject, so they fall to the implicit deny without any extra statement.

Exercise 2: design a subnet plan

Task. The VPC is 10.20.0.0/16. Plan six subnets for three Availability Zones: one public /24 and one private /20 per zone, with no overlaps. AWS reserves five addresses in every subnet, so a /24 gives 251 usable addresses.

Refresher: VPC Fundamentals.

Python Exercise 2: find the overlaps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Solution. The first private subnet, 10.20.0.0/20, covers 10.20.0.0 to 10.20.15.255, so it swallows all three public subnets. Move the private subnets above the public range, on /20 boundaries (multiples of 16 in the third octet):

Python
plan = {
    "public-a":  "10.20.0.0/24",
    "public-b":  "10.20.1.0/24",
    "public-c":  "10.20.2.0/24",
    "private-a": "10.20.16.0/20",
    "private-b": "10.20.32.0/20",
    "private-c": "10.20.48.0/20",
}

This leaves 10.20.64.0 and above free for future subnets (databases, a second environment). A common beginner error is a CIDR like 10.20.8.0/20, which has host bits set: ip_network raises an error for it, and AWS rejects it too. Leave room to grow, and never overlap the CIDR of a network you may peer with later (connectivity lesson).

Exercise 3: S3 lifecycle rules

Task. Log files should stay in Standard for 30 days, move to Standard-IA, move to Glacier after 90 days, and be deleted after 365 days. Write the rules so the checks pass.

Refresher: Storage Classes and Lifecycle Rules.

Python Exercise 3: complete the lifecycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Solution. The rule list has no expiration, so old objects stay in Glacier (and keep costing money) forever. Add (365, "EXPIRED"). In real S3 the same policy is this JSON (read-only):

JSON
{
  "Rules": [
    {
      "ID": "logs-tiering",
      "Status": "Enabled",
      "Filter": { "Prefix": "logs/" },
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 90, "StorageClass": "GLACIER" }
      ],
      "Expiration": { "Days": 365 }
    }
  ]
}

Watch for real-world traps: objects smaller than 128 KB are not moved to Standard-IA by default, and Glacier classes have minimum storage durations, so an expiration before that minimum still bills the remainder. For versioned buckets you also need NoncurrentVersionExpiration, or old versions pile up.

Exercise 4: a Lambda handler

Task. Write an API Gateway proxy handler for POST /sum. The request body is JSON like {"numbers": [1, 2, 3]}. Return status 200 and a JSON string body with the total, or 400 for bad input.

Refresher: Lambda Functions and API Gateway. With the proxy integration, body must be a string, not an object.

Python Exercise 4: fix the response shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Solution. The success path returns a dictionary as body. API Gateway's proxy integration requires a string there, and a real deployment would answer with a 502 "malformed Lambda proxy response". Wrap it with json.dumps:

Python
return {"statusCode": 200, "body": json.dumps({"total": total})}

Also add a Content-Type: application/json header in a real function. Notice how the exception handling covers four different bad inputs (invalid JSON, a missing key, a wrong type and an empty body) with one except. Input validation is part of the job: never assume the event looks the way you expect.

Exercise 5: estimate a monthly bill

Task. Estimate one month for this setup: two virtual machines running all month (730 hours), 200 GB of block storage, 500 GB in object storage, 300 GB of data transferred out to the internet (the first 100 GB are free), and one NAT gateway running all month that processes 150 GB. The rates are invented for the exercise.

Refresher: Cost Management.

Python Exercise 5: do not forget the NAT gateway

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Solution. The estimate is $39.60 short because it leaves out the NAT gateway, which has an hourly charge (730 hours x 0.045 = $32.85) and a per-GB processing charge (150 GB x 0.045 = $6.75). Add them to the dictionary:

Python
"nat gateway hours": u["nat_gateways"] * u["hours"] * r["nat_hour"],
"nat gateway data": u["nat_gb"] * r["nat_gb"],

With the two lines added the total becomes $114.30. The lesson of the exercise: the "small" supporting services (NAT, load balancers, public IPv4 addresses, cross-AZ transfer) often cost as much as the compute. Always list every resource, including the ones that do no visible work.

Exercise 6: troubleshooting scenarios

These are thought exercises. Decide your answer before reading it. The full checklists are in Common Mistakes and Troubleshooting.

Scenario A. You launch an EC2 instance in a public subnet and SSH to its public IP. The connection hangs and finally times out. What do you check?

Answer. A timeout (no reply at all) points at the network path, not the credentials. Check, in order: the security group allows inbound TCP 22 from your IP; the subnet's route table has a 0.0.0.0/0 route to an internet gateway; the instance has a public IP; the network ACL allows port 22 inbound and the ephemeral ports outbound. A "connection refused" or "permission denied (publickey)" would mean the network is fine.

Scenario B. A Lambda function placed in a VPC calls a public API and times out, though it worked before it was moved into the VPC.

Answer. A function in a VPC uses private subnets, and has no internet path of its own. Give those subnets a route to a NAT gateway in a public subnet, or use a VPC endpoint if the target is an AWS service.

Scenario C. An application role can list an S3 bucket but every GetObject returns AccessDenied. The objects are encrypted with a customer managed KMS key.

Answer. Reading an SSE-KMS object also needs kms:Decrypt on the key, through the key policy or the role. S3 permissions alone are not enough.

Scenario D. The ALB returns 502 Bad Gateway for a few seconds after every deployment.

Answer. Likely the target closed connections that the ALB still considered open (for example, the app's keep-alive timeout is shorter than the ALB's idle timeout), or tasks were deregistered without draining. Increase the app's keep-alive time above the ALB idle timeout and use deregistration delay so in-flight requests finish.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which resource ARN must the s3:ListBucket action use in a policy?

    ListBucket is a bucket-level action, so it matches the bucket ARN. Object-level actions such as GetObject use object ARNs with a key pattern.
  2. 2. A subnet has the CIDR 10.0.1.0/24. How many addresses can you actually assign to instances?

    AWS reserves five addresses in every subnet (the network address, the VPC router, DNS, a future-use address and the broadcast address), leaving 251 of the 256.
  3. 3. Why can a Lambda proxy handler that returns a dictionary as body cause a 502 from API Gateway?

    The proxy integration passes the response through, and it requires body to be a string, so serialize JSON with json.dumps first.
  4. 4. Your SSH connection to an EC2 instance times out instead of being refused. What does that suggest?

    A silent timeout means no answer came back, typically a blocking security group or NACL rule, or a missing route. Wrong keys produce a quick authentication error instead.

Summary

  • Policies: pair each action with the right resource type (bucket ARN versus object ARN), and rely on the implicit deny instead of listing what is not allowed.
  • Networking: plan CIDRs on proper boundaries, leave room to grow and check overlaps with a tool, not by eye.
  • Storage: lifecycle rules need an expiration step or old data costs money forever.
  • Lambda: validate input and return the exact response shape the integration expects.
  • Costs: count every resource; NAT gateways and data transfer are the usual surprises.
  • Troubleshooting: the symptom (timeout, refusal, AccessDenied) tells you which layer to inspect first.

Next: Common Mistakes and Troubleshooting