TExcelTAD
Home › AWS Cloud › AWS Exercises

AWS Exercises

Time to practise! Each exercise has a starter playground that runs as it is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. The solutions are hidden below each exercise; try for a few minutes before you peek.

All prices are example prices, chosen to keep the arithmetic simple.

# Exercise Lesson
1 Subnet planner VPC and subnets
2 Explicit deny IAM policies
3 Open SSH finder Security groups
4 Lambda bill Lambda
5 Target tracking Auto Scaling
6 DynamoDB capacity DynamoDB
7 Storage class picker S3 storage classes
8 Weighted DNS Route 53

1. Subnet planner

Split the VPC 10.50.0.0/16 into /24 subnets and print the first three, each with its number of usable addresses (remember that AWS reserves 5 per subnet).

Expected:

text
10.50.0.0/24 251
10.50.1.0/24 251
10.50.2.0/24 251
python · try it yourself
import ipaddress

vpc = ipaddress.ip_network("10.50.0.0/16")
# TODO: use vpc.subnets(new_prefix=...) and print the first three
subnets = [vpc]
for net in subnets[:3]:
    print(net, net.num_addresses)
10.50.0.0/16 65536
Show solution
python
import ipaddress
from itertools import islice

vpc = ipaddress.ip_network("10.50.0.0/16")
for net in islice(vpc.subnets(new_prefix=24), 3):
    print(net, net.num_addresses - 5)

2. Explicit deny

Complete evaluate(statements, action) so that it follows IAM's rules: an explicit Deny wins, otherwise a matching Allow allows, otherwise the result is an implicit deny. Use fnmatchcase for wildcards.

Expected:

text
s3:GetObject ALLOW
s3:DeleteObject DENY
ec2:RunInstances IMPLICIT_DENY
python · try it yourself
from fnmatch import fnmatchcase

statements = [
    {"Effect": "Allow", "Action": "s3:*"},
    {"Effect": "Deny", "Action": "s3:Delete*"},
]

def evaluate(statements, action):
    # TODO: implement explicit deny > allow > implicit deny
    return "ALLOW"

for action in ["s3:GetObject", "s3:DeleteObject", "ec2:RunInstances"]:
    print(action, evaluate(statements, action))
s3:GetObject ALLOW
s3:DeleteObject ALLOW
ec2:RunInstances ALLOW
Show solution
python
def evaluate(statements, action):
    matching = [s for s in statements if fnmatchcase(action, s["Action"])]
    if any(s["Effect"] == "Deny" for s in matching):
        return "DENY"
    if any(s["Effect"] == "Allow" for s in matching):
        return "ALLOW"
    return "IMPLICIT_DENY"

3. Open SSH finder

Print the IDs of the security groups that allow port 22 from 0.0.0.0/0. A rule is a tuple (from_port, to_port, cidr), so also catch port ranges that include 22.

Expected:

text
sg-bastion
sg-legacy
python · try it yourself
groups = {
    "sg-web":     [(443, 443, "0.0.0.0/0"), (80, 80, "0.0.0.0/0")],
    "sg-bastion": [(22, 22, "0.0.0.0/0")],
    "sg-admin":   [(22, 22, "198.51.100.0/24")],
    "sg-legacy":  [(0, 1024, "0.0.0.0/0")],
}

for group_id, rules in groups.items():
    # TODO: check whether any rule opens port 22 to the world
    open_ssh = False
    if open_ssh:
        print(group_id)
print("done")
done
Show solution
python
for group_id, rules in groups.items():
    open_ssh = any(lo <= 22 <= hi and cidr == "0.0.0.0/0" for lo, hi, cidr in rules)
    if open_ssh:
        print(group_id)

4. Lambda bill

Compute the monthly cost of a function with 10 million invocations, 200 ms average duration and 512 MB memory, without free tier. Example prices: $0.20 per million requests and $0.0000166667 per GB-second. Round to cents.

Expected: requests $2.00, compute $16.67, total $18.67

python · try it yourself
invocations = 10_000_000
duration_s = 0.2
memory_gb = 512 / 1024

request_cost = 0.0      # TODO
compute_cost = 0.0      # TODO: GB-seconds x price
print(f"requests ${request_cost:.2f}, compute ${compute_cost:.2f}, total ${request_cost + compute_cost:.2f}")
requests $0.00, compute $0.00, total $0.00
Show solution
python
request_cost = invocations / 1_000_000 * 0.20
gb_seconds = invocations * duration_s * memory_gb       # 1,000,000 GB-seconds
compute_cost = gb_seconds * 0.0000166667
print(f"requests ${request_cost:.2f}, compute ${compute_cost:.2f}, total ${request_cost + compute_cost:.2f}")

5. Target tracking

Write desired_capacity(current, metric, target, minimum, maximum) using the target-tracking formula ceil(current × metric / target), clamped to the min and max.

Expected:

text
4 instances at 75% CPU -> 6
4 instances at 20% CPU -> 2
8 instances at 95% CPU -> 10
python · try it yourself
import math

def desired_capacity(current, metric, target, minimum, maximum):
    # TODO
    return current

for current, cpu in [(4, 75), (4, 20), (8, 95)]:
    print(f"{current} instances at {cpu}% CPU -> {desired_capacity(current, cpu, 50, 2, 10)}")
4 instances at 75% CPU -> 4
4 instances at 20% CPU -> 4
8 instances at 95% CPU -> 8
Show solution
python
def desired_capacity(current, metric, target, minimum, maximum):
    wanted = math.ceil(current * metric / target)
    return max(minimum, min(maximum, wanted))

For 4 instances at 20%: ceil(1.6) = 2. For 8 at 95%: ceil(15.2) = 16, clamped to 10.

6. DynamoDB capacity

Items are 7 KB. Compute the WCUs for 40 writes per second and the RCUs for 100 strongly consistent and 100 eventually consistent reads per second. (1 WCU = 1 KB write, 1 RCU = one strong 4 KB read or two eventual reads, sizes rounded up.)

Expected: WCU 280, strong RCU 200, eventual RCU 100

python · try it yourself
import math

item_kb = 7
wcu = 0             # TODO
strong_rcu = 0      # TODO
eventual_rcu = 0    # TODO
print(f"WCU {wcu}, strong RCU {strong_rcu}, eventual RCU {eventual_rcu}")
WCU 0, strong RCU 0, eventual RCU 0
Show solution
python
wcu = math.ceil(item_kb / 1) * 40                 # 7 x 40
strong_rcu = math.ceil(item_kb / 4) * 100         # 2 x 100
eventual_rcu = math.ceil(math.ceil(item_kb / 4) * 100 / 2)
print(f"WCU {wcu}, strong RCU {strong_rcu}, eventual RCU {eventual_rcu}")

7. Storage class picker

For each dataset, print the cheapest class per month among Standard ($0.023/GB, no retrieval fee), Standard-IA ($0.0125/GB + $0.01 per GB read) and Glacier Instant Retrieval ($0.004/GB + $0.03 per GB read). read_gb is how many GB are read per month.

Expected:

text
website-images STANDARD
quarterly-reports GLACIER_IR
monthly-exports STANDARD_IA
python · try it yourself
PRICES = {"STANDARD": (0.023, 0.0), "STANDARD_IA": (0.0125, 0.01), "GLACIER_IR": (0.004, 0.03)}
datasets = {"website-images": (200, 600), "quarterly-reports": (500, 40), "monthly-exports": (1000, 600)}

for name, (stored_gb, read_gb) in datasets.items():
    # TODO: compute the cost of each class and pick the cheapest
    best = "STANDARD"
    print(name, best)
website-images STANDARD
quarterly-reports STANDARD
monthly-exports STANDARD
Show solution
python
for name, (stored_gb, read_gb) in datasets.items():
    costs = {cls: stored_gb * store + read_gb * read for cls, (store, read) in PRICES.items()}
    best = min(costs, key=costs.get)
    print(name, best)

For the monthly exports: Standard $23.00, Standard-IA $18.50, Glacier IR $22.00.

8. Weighted DNS

Route 53 answers in proportion to record weights. Distribute 200 queries over the records blue (weight 3) and green (weight 1) deterministically: query i gets the record whose cumulative weight range contains i % total_weight.

Expected: {'blue': 150, 'green': 50}

python · try it yourself
records = [("blue", 3), ("green", 1)]
total = sum(w for _, w in records)
counts = {name: 0 for name, _ in records}

for i in range(200):
    slot = i % total
    # TODO: find the record whose range contains slot, then count it
    counts["blue"] += 1
print(counts)
{'blue': 200, 'green': 0}
Show solution
python
for i in range(200):
    slot = i % total
    for name, weight in records:
        if slot < weight:
            counts[name] += 1
            break
        slot -= weight
print(counts)

Test yourself

How many usable addresses does a /26 subnet have in AWS?

  1. 64
  2. 62
  3. 59
  4. 26

An ASG with min 2 / max 10 has 6 instances at 25% CPU and targets 50%. What is the new desired capacity?

  1. 2
  2. 3
  3. 6
  4. 12

A security group rule allows ports 0–1024 from 0.0.0.0/0. Is SSH open to the world?

  1. No, only 0 and 1024
  2. Yes, port 22 is inside the range
  3. Only on IPv6
  4. Only with a NACL