Azure & Google Cloud Exercises
Each exercise is a small piece of the logic the clouds apply for you, written as a pure function with the calls already in place. Run the starter first: it prints placeholder answers, which shows what the calls expect. Fill in the code marked TODO until the output matches the expected output, then compare with the solution.
Exercise 1: Usable addresses per cloud
Topics: VNets and Global VPCs
Return how many addresses you can use in a subnet on each cloud. AWS and Azure reserve 5 addresses per subnet, Google Cloud 4. Return None if the subnet is smaller than the cloud allows (AWS's smallest is /28, Azure's and Google Cloud's /29).
import ipaddress
RESERVED = {"aws": 5, "azure": 5, "gcp": 4}
MIN_PREFIX = {"aws": 28, "azure": 29, "gcp": 29}
def usable(cloud, cidr):
# TODO: parse the CIDR, reject prefixes longer than MIN_PREFIX, subtract RESERVED
return 0
for cidr in ["10.0.0.0/24", "10.0.1.0/28", "10.0.2.0/29"]:
print(cidr, {c: usable(c, cidr) for c in RESERVED})10.0.0.0/24 {'aws': 0, 'azure': 0, 'gcp': 0}
10.0.1.0/28 {'aws': 0, 'azure': 0, 'gcp': 0}
10.0.2.0/29 {'aws': 0, 'azure': 0, 'gcp': 0}
Expected output:
10.0.0.0/24 {'aws': 251, 'azure': 251, 'gcp': 252}
10.0.1.0/28 {'aws': 11, 'azure': 11, 'gcp': 12}
10.0.2.0/29 {'aws': None, 'azure': 3, 'gcp': 4}Show solution
def usable(cloud, cidr):
net = ipaddress.ip_network(cidr)
if net.prefixlen > MIN_PREFIX[cloud]:
return None
return net.num_addresses - RESERVED[cloud]A /29 on Azure leaves only 3 usable addresses: fine for a tiny appliance subnet, useless for anything that scales.
Exercise 2: Evaluate an NSG
Topics: Security Groups, NSGs and VPC Firewall Rules
Return (access, rule_name) for an inbound packet: sort rules by ascending priority, return the first rule whose source CIDR contains the address and whose port matches ("*" matches any port). If nothing matches, the default rule ("Deny", "DenyAllInBound") applies.
import ipaddress
def nsg_decide(rules, src, port):
# TODO: first match by ascending priority
return ("?", "?")
rules = [
{"name": "allow-https", "priority": 200, "source": "0.0.0.0/0", "port": 443, "access": "Allow"},
{"name": "block-scanner", "priority": 150, "source": "198.51.100.0/24", "port": "*", "access": "Deny"},
{"name": "allow-ssh-office", "priority": 300, "source": "203.0.113.0/28", "port": 22, "access": "Allow"},
]
for src, port in [("192.0.2.10", 443), ("198.51.100.20", 443), ("203.0.113.5", 22), ("192.0.2.10", 22)]:
print(src, port, nsg_decide(rules, src, port))192.0.2.10 443 ('?', '?')
198.51.100.20 443 ('?', '?')
203.0.113.5 22 ('?', '?')
192.0.2.10 22 ('?', '?')
Expected output:
192.0.2.10 443 ('Allow', 'allow-https')
198.51.100.20 443 ('Deny', 'block-scanner')
203.0.113.5 22 ('Allow', 'allow-ssh-office')
192.0.2.10 22 ('Deny', 'DenyAllInBound')Show solution
def nsg_decide(rules, src, port):
for r in sorted(rules, key=lambda r: r["priority"]):
if ipaddress.ip_address(src) in ipaddress.ip_network(r["source"]) and r["port"] in (port, "*"):
return r["access"], r["name"]
return "Deny", "DenyAllInBound"The scanner is blocked only because its rule has a lower number (150) than allow-https (200). Swap the priorities and it gets in.
Exercise 3: Inherited Google Cloud roles
Topics: Google Cloud IAM, Accounts, Subscriptions and Projects
Return the sorted list of roles a member has on a resource, collecting bindings from the resource and every ancestor.
parent = {"projects/shop-prod": "folders/prod", "folders/prod": "organizations/acme",
"projects/shop-dev": "folders/dev", "folders/dev": "organizations/acme"}
policies = {
"organizations/acme": {"roles/viewer": ["group:auditors"]},
"folders/prod": {"roles/compute.admin": ["group:sre"], "roles/viewer": ["group:devs"]},
"folders/dev": {"roles/editor": ["group:devs"]},
"projects/shop-prod": {"roles/run.developer": ["group:devs"]},
}
def effective_roles(member, resource):
# TODO: walk from resource up through parent, collecting roles that list the member
return []
for m in ["group:devs", "group:sre", "group:auditors"]:
print(m, "prod:", effective_roles(m, "projects/shop-prod"), "dev:", effective_roles(m, "projects/shop-dev"))group:devs prod: [] dev: []
group:sre prod: [] dev: []
group:auditors prod: [] dev: []
Expected output:
group:devs prod: ['roles/run.developer', 'roles/viewer'] dev: ['roles/editor']
group:sre prod: ['roles/compute.admin'] dev: []
group:auditors prod: ['roles/viewer'] dev: ['roles/viewer']Show solution
def effective_roles(member, resource):
roles = set()
node = resource
while node:
for role, members in policies.get(node, {}).items():
if member in members:
roles.add(role)
node = parent.get(node)
return sorted(roles)Exercise 4: Parse an Azure resource ID
Topics: Three Clouds, One Mental Model
Return a dict with subscription, resource_group, namespace, type (namespace plus every type segment) and name (every name segment joined with /).
def parse_resource_id(rid):
parts = rid.strip("/").split("/")
# TODO: subscriptions/<sub>/resourceGroups/<rg>/providers/<namespace>/<type>/<name>[/<type>/<name>...]
return {"subscription": None, "resource_group": None, "namespace": None, "type": None, "name": None}
for rid in [
"/subscriptions/1111/resourceGroups/rg-app/providers/Microsoft.Compute/virtualMachines/vm-1",
"/subscriptions/1111/resourceGroups/rg-net/providers/Microsoft.Network/virtualNetworks/vnet-1/subnets/snet-app",
]:
print(parse_resource_id(rid)){'subscription': None, 'resource_group': None, 'namespace': None, 'type': None, 'name': None}
{'subscription': None, 'resource_group': None, 'namespace': None, 'type': None, 'name': None}
Expected output:
{'subscription': '1111', 'resource_group': 'rg-app', 'namespace': 'Microsoft.Compute', 'type': 'Microsoft.Compute/virtualMachines', 'name': 'vm-1'}
{'subscription': '1111', 'resource_group': 'rg-net', 'namespace': 'Microsoft.Network', 'type': 'Microsoft.Network/virtualNetworks/subnets', 'name': 'vnet-1/snet-app'}Show solution
def parse_resource_id(rid):
parts = rid.strip("/").split("/")
out = {"subscription": parts[1], "resource_group": parts[3], "namespace": parts[5]}
out["type"] = out["namespace"] + "/" + "/".join(parts[6::2])
out["name"] = "/".join(parts[7::2])
return outReal IDs are case-insensitive (resourcegroups vs resourceGroups both appear in the wild); production code should compare segment names case-insensitively.
Exercise 5: Collapse per-AZ subnets for Azure
Topics: VNets and Global VPCs
An AWS design has one subnet per tier per AZ. Azure subnets span zones, so produce one subnet per tier, in the order tiers first appear, carving consecutive blocks of the given prefix out of the VNet range.
import ipaddress
aws_subnets = [
("public", "eu-west-1a", "10.20.0.0/20"), ("public", "eu-west-1b", "10.20.16.0/20"),
("app", "eu-west-1a", "10.20.48.0/20"), ("app", "eu-west-1b", "10.20.64.0/20"),
("data", "eu-west-1a", "10.20.96.0/20"), ("data", "eu-west-1b", "10.20.112.0/20"),
]
def to_azure(subnets, vnet_cidr, prefix):
# TODO: unique tiers in order; next block from ipaddress.ip_network(vnet_cidr).subnets(new_prefix=prefix)
return [(f"snet-{tier}", "?") for tier, _, _ in subnets]
for name, cidr in to_azure(aws_subnets, "10.30.0.0/16", 20):
print(name, cidr)snet-public ?
snet-public ?
snet-app ?
snet-app ?
snet-data ?
snet-data ?
Expected output:
snet-public 10.30.0.0/20
snet-app 10.30.16.0/20
snet-data 10.30.32.0/20Show solution
def to_azure(subnets, vnet_cidr, prefix):
tiers = list(dict.fromkeys(t for t, _, _ in subnets))
blocks = ipaddress.ip_network(vnet_cidr).subnets(new_prefix=prefix)
return [(f"snet-{t}", str(next(blocks))) for t in tiers]dict.fromkeys keeps the first-seen order while removing duplicates.
Exercise 6: Which CI token is trusted?
Topics: Workload Identity Federation and CI Logins
Implement both checks for GitHub OIDC tokens: Azure trusts a token if its sub exactly equals one of the federated credentials' subjects; the Google Cloud provider trusts it if repository_owner is the given owner and its environment is in the allowed set.
def azure_allows(credentials, sub):
# TODO: exact subject match
return None
def gcp_allows(claims, owner, allowed_envs):
# TODO: attribute condition on owner + environment
return None
azure_creds = ["repo:acme/shop:environment:production", "repo:acme/shop:ref:refs/heads/main"]
tokens = [
{"sub": "repo:acme/shop:environment:production", "repository_owner": "acme", "environment": "production"},
{"sub": "repo:acme/shop:ref:refs/heads/main", "repository_owner": "acme", "environment": None},
{"sub": "repo:acme/shop:environment:staging", "repository_owner": "acme", "environment": "staging"},
{"sub": "repo:other/shop:environment:production", "repository_owner": "other", "environment": "production"},
]
for t in tokens:
print(f"{t['sub']:<42} azure={azure_allows(azure_creds, t['sub'])!s:<6} gcp={gcp_allows(t, 'acme', {'production'})}")repo:acme/shop:environment:production azure=None gcp=None
repo:acme/shop:ref:refs/heads/main azure=None gcp=None
repo:acme/shop:environment:staging azure=None gcp=None
repo:other/shop:environment:production azure=None gcp=None
Expected output:
repo:acme/shop:environment:production azure=True gcp=True
repo:acme/shop:ref:refs/heads/main azure=True gcp=False
repo:acme/shop:environment:staging azure=False gcp=False
repo:other/shop:environment:production azure=False gcp=FalseShow solution
def azure_allows(credentials, sub):
return any(c == sub for c in credentials)
def gcp_allows(claims, owner, allowed_envs):
return claims["repository_owner"] == owner and claims.get("environment") in allowed_envsThe main branch is trusted on Azure because a second federated credential names it. Whether that is right depends on what the identity may do: for production deployments, trust only the production environment, whose protection rules require approval.
Test yourself
In Exercise 2, why is the scanner blocked on port 443 even though an allow rule matches too?
- Deny always wins in NSGs
- Its rule has a lower priority number and NSGs stop at the first match
- The allow rule is invalid
- Port 443 is blocked by default
In Exercise 3, why does group:auditors have roles/viewer on both projects?
- It was granted on each project
- It was granted on the organization and inherits down
- Viewer is automatic
- Because of a deny policy