Course contents 10 / 16

10 / 16 · Infrastructure

Cloud building blocks

What a cloud is made of, independent of the provider: compute as virtual machines, containers and functions; block, object and file storage; networks and security groups; identity and least privilege; shared responsibility, regions and zones, and the arithmetic of cost.

On this page 10

The previous note described a bucket, its region and its access as code, and took for granted what a bucket, a region and an access policy are. A cloud provider sells a few hundred services, but nearly all of them are combinations of a handful of building blocks: something that runs code, something that stores bytes, a network between them, an identity system that decides who may do what, and a map of locations that fail independently. This note goes through those blocks without tying them to one provider, says what each protects against and what it costs, and gives the names that AWS, Google Cloud and Yandex Cloud use for them.

Conventions. Provider names and facts are as of October 2026. Prices in the worked examples are toy values chosen to be of the same shape as public list prices, not quotes; real prices differ by region, change over time and are on each provider’s pricing pages. Python 3.14.7 for the one script.

Baseline: rent a server#

Before clouds, a team that needed machines rented them by the month in a data centre, or bought them and paid for rack space. Ordering took days or weeks. The capacity was fixed: enough for the peak of the year, so idle most of the time, and still too little when the peak was larger than planned. One data centre was one place where power, cooling or the network could fail. And everything above the hardware, the operating system, the database, the backups, the load balancer, was the team’s to install and run.

A cloud changes three things. Every resource is created and destroyed by an API call, in seconds, which is what made the infrastructure as code of the previous note possible. Resources are billed by usage: per second of a running machine, per gigabyte stored per month, per gigabyte sent. And the provider runs the same services in many locations designed to fail independently.

Compute: virtual machines, containers, functions#

Virtual machines (instances) are guests on the provider’s hypervisor, the mechanism of the virtualization note. An instance has a type that fixes its virtual CPUs and memory (families differ in the ratio of the two, and some add GPUs or fast local disks), boots from an image, and is billed per second while it runs. Everything inside, from the kernel up, is yours: updates, configuration, monitoring. Groups of identical instances behind a load balancer, created and replaced from one template, are how the immutable infrastructure of the previous note is usually built.

Containers come in two managed forms. A serverless container service runs an image when told to, scales the number of copies with the load and bills for their running time, without showing any machine. A managed Kubernetes service runs the control plane of a cluster, the subject of the next section, while the worker machines are instances that you choose, or that the provider manages too.

Functions (function as a service) go one step further: you upload a function, the platform runs it once per event (an HTTP request, a file arriving in a bucket, a message in a queue) and bills per invocation and per gigabyte-second of memory held while it runs. With no events, a function costs nothing. The constraints are the price: an invocation runs for a limited time (at most 15 minutes on AWS Lambda), keeps no state between invocations except in external storage, and a first request after a quiet period waits for a cold start while the platform loads the code.

Worked example. When is a function cheaper than a machine? A toy machine at $0.08 per hour costs 0.08×730=58.400.08 \times 730 = 58.40 dollars a month, at any load it can handle. A toy function holds 0.5 GB for 100 ms per request, at 1.667×10−51.667 \times 10^{-5} dollars per gigabyte-second plus 0.20 dollars per million requests:

creq=0.5×0.1×1.667×10−5+0.2×10−6=8.33×10−7+2.0×10−7=$1.033×10−6.\begin{aligned} c_{\text{req}} &= 0.5 \times 0.1 \times 1.667 \times 10^{-5} + 0.2 \times 10^{-6} \\ &= 8.33 \times 10^{-7} + 2.0 \times 10^{-7} = \$1.033 \times 10^{-6} . \end{aligned}

The two cost the same at 58.40/(1.033×10−6)≈56.5×10658.40 / (1.033 \times 10^{-6}) \approx 56.5 \times 10^6 requests a month, an average of 56.5×106/(730×3,600)≈21.556.5 \times 10^6 / (730 \times 3{,}600) \approx 21.5 requests per second. Below that the function is cheaper, and far cheaper for a service that is idle most of the day; above it, the machine is, as long as one machine can carry the load.

Storage: block, object and file#

Block storageObject storageFile storage
What it isa virtual diska flat map from keys to objectsa shared network file system
Interfacea block device: the OS puts a file system on itHTTP: PUT and GET whole objects by keyPOSIX files over NFS or SMB
Attached toone machine at a time, in one zonenothing: any client with permissionmany machines at once
Scopea zonea region, copies in several zonesa zone or a region
Changing a partoverwrite any blockrewrite the whole objectwrite into a file
Typical usea database’s data directory, a boot diskbackups, logs, images, static files, data setsa directory shared by a fleet
Billed forprovisioned size and performancestored bytes, requests, bytes sent outprovisioned or used size

Block storage is a disk that lives on the network: it survives when its machine is stopped or replaced and can be attached to another machine in the same zone. Its performance is part of the order, a number of I/O operations per second and of megabytes per second; a snapshot copies it to object storage, which is how it is backed up and moved to another zone. The files note describes what the operating system builds on top of a block device.

Object storage has no directories, no partial writes and no attachment: a bucket holds objects addressed by keys, read and written whole over HTTP. In exchange it scales to any size, and a provider replicates every object across several zones; AWS designs S3 for 99.999999999 % (eleven nines) durability of objects over a year (AWS, S3 documentation). An object store is a good place for anything written once and read many times, and the wrong place for a database’s files, which change a few blocks at a time.

File storage is the old shared drive: a file system served over the network, mounted by many machines at once. It is convenient for software that expects a shared directory and slower and more expensive per gigabyte than either of the other two.

Networks: VPC, subnets, security groups#

A virtual private cloud (VPC) is a private network in the provider’s infrastructure, with an address range chosen by you, usually a private range of the networking note. It is divided into subnets, each a smaller prefix tied to one zone on AWS and Yandex Cloud (to a region on Google Cloud). A public subnet has a route to an internet gateway, and its machines can have public addresses; a private subnet has none, and its machines reach the internet, if at all, through a NAT gateway that allows only outgoing connections. Load balancers go into public subnets, and everything else into private ones.

Worked example. Plan a VPC 10.0.0.0/16 with a public and a private /20 per zone, in three zones:

import ipaddress

vpc = ipaddress.ip_network("10.0.0.0/16")
blocks = list(vpc.subnets(new_prefix=20))        # all /20 blocks of the VPC
print(len(blocks), "blocks of", blocks[0].num_addresses, "addresses")
plan = {f"public-{z}": blocks[z - 1] for z in (1, 2, 3)}
plan |= {f"private-{z}": blocks[8 + z - 1] for z in (1, 2, 3)}
for name, net in plan.items():
    # the provider keeps the network address, the next three and the broadcast address
    print(f"{name:10} {str(net):15} usable {net.num_addresses - 5}")
print("spare blocks:", len(blocks) - len(plan))
$ python3.14 subnets.py
16 blocks of 4096 addresses
public-1   10.0.0.0/20     usable 4091
public-2   10.0.16.0/20    usable 4091
public-3   10.0.32.0/20    usable 4091
private-1  10.0.128.0/20   usable 4091
private-2  10.0.144.0/20   usable 4091
private-3  10.0.160.0/20   usable 4091
spare blocks: 10

A /16 has 216=65,5362^{16} = 65{,}536 addresses and a /20 has 212=4,0962^{12} = 4{,}096, so the VPC holds 220−16=162^{20-16} = 16 such blocks. AWS reserves five addresses in each subnet (the network address, the next three for the router, DNS and future use, and the broadcast address), so 4,096−5=4,0914{,}096 - 5 = 4{,}091 are usable; other providers reserve a similar handful. Starting the private subnets at 10.0.128.0 keeps the two kinds in separate halves of the range, which makes rules and routes easy to read, and leaves ten blocks for zones and tiers added later. Address ranges are hard to change once machines use them, and two VPCs that must be connected later cannot overlap, so the plan deserves the minute it takes.

Security groups are firewalls attached to machines (to their network interfaces), not to subnets. A group holds only allow rules: a protocol, a port range and a source, which is either a prefix or another security group. They are stateful: when a rule admits a connection, the replies of that connection are admitted too, without a rule for them, because the firewall tracks connections. Referring to groups instead of addresses is what keeps rules correct as machines come and go:

GroupAllows inFrom
lbTCP 4430.0.0.0/0, the whole internet
appTCP 8080the group lb
dbTCP 5432the group app

Any machine that joins app can reach the database, and nothing else can, whatever its address. A misconfigured rule that opens port 5432 to 0.0.0.0/0 is one of the commonest causes of a data breach in the cloud, and one reason that security rules belong in reviewed code.

Identity and access: principals, policies, least privilege#

Every API call to a cloud is made by a principal, authenticated, and checked against policies before it is executed. The same model as the Unix permissions of the systems course, with far finer grain: not read, write and execute on a file, but each of thousands of API actions on each resource.

  • Principals are human users (often signed in through the company’s identity provider), groups of them, and machine identities: roles or service accounts that a virtual machine, a container or a CI job assumes, receiving credentials that expire within an hour or so instead of a long-lived key.
  • A policy says which principal may perform which actions on which resources, under which conditions (from which network, with multi-factor authentication, before which date).
  • The evaluation is deny by default: a request is allowed only if some policy allows it, and an explicit deny anywhere overrides every allow.

Worked example. The role of the web servers needs to write access logs into the bucket of the previous note and read its own configuration, nothing more. An AWS policy for that:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "WriteAccessLogs",
      "Effect": "Allow",
      "Action": ["s3:PutObject"],
      "Resource": "arn:aws:s3:::example-web-logs-prod/access/*"
    },
    {
      "Sid": "ReadOwnConfig",
      "Effect": "Allow",
      "Action": ["s3:GetObject"],
      "Resource": "arn:aws:s3:::example-web-config-prod/web/*"
    }
  ]
}

Version is the version of the policy language, not a date of this policy. Each statement allows one action on objects under one prefix: arn:aws:s3:::BUCKET/PREFIX* is the resource name (ARN) of every object whose key starts with the prefix. A request by the role to read a log (s3:GetObject on example-web-logs-prod/access/...) matches no statement and is denied by default; so is deleting any object, or listing the bucket. If the role’s credentials leak, the attacker can add log files and read one service’s configuration, not empty the account. That is least privilege: grant the actions a principal needs, on the resources it needs, and nothing that might be convenient later. In practice permissions grow by accretion, and providers offer tools that compare granted permissions with those actually used, so that the unused ones can be removed. A CI job that deploys should also get a role, by exchanging a short-lived token from the CI system for cloud credentials (OIDC federation), not a stored access key; the CI note explains why stored keys in pipelines are dangerous.

Managed services and the shared-responsibility model#

A managed service is one whose software the provider operates: a managed PostgreSQL patches itself, takes backups, and fails over to a standby; a managed queue, DNS zone, load balancer or Kubernetes control plane likewise. You configure it and pay a premium over running the same software on instances, in exchange for not running it.

Security and operations are then split. The provider is responsible for the security of the cloud: buildings, hardware, the hypervisor, the network between data centres, and the software of each managed service. The customer is responsible for security in the cloud: their data, their identities and policies, their network rules, and whatever software they run themselves (AWS, shared responsibility model). Where the line falls depends on the block:

You are responsible forVirtual machineManaged containersFunctionManaged database
Data, identities, policies, network rulesyesyesyesyes
Application code and its dependenciesyesyesyes(schema, queries)
Container imageyes
Operating system, its patchesyes
Runtime, scaling, failoveryespartly

The row that is never empty is the first. A provider does not stop a customer from making a bucket public, granting an over-broad role or opening a database port to the internet, and most cloud breaches come from that row, not from the provider’s part.

Regions and availability zones#

A region is a geographic area, such as Frankfurt or Moscow, with several availability zones. A zone is one or more data centres with independent power, cooling and network connections, far enough from the others that a fire, flood or power failure is unlikely to hit two, and close enough, a few milliseconds of round trip, that data can be replicated between zones synchronously. On Yandex Cloud, for example, the region ru-central1 has the zones ru-central1-a, -b and -d, with a fourth, -e, and a separate bare-metal zone in October 2026 (Yandex Cloud, availability zones). Resources have a scope: a machine and its disk belong to one zone, a load balancer or a bucket to a region, and some services, such as DNS and identity, are global.

Figure

A service in one region with three availability zones

A service in one region with three availability zonesA region with three zones. At the top a load balancer in the public subnets of every zone, below it two app instances in each zone. In zone 1 the database primary, in zone 2 its synchronous standby, with a replication arrow between them. Each zone lists a public and a private /20 subnet inside the VPC 10.0.0.0/16. Security groups let only the load balancer reach the app and only the app reach the database. At the bottom object storage with copies in every zone. In the last step zone 1 is crossed out and the standby in zone 2 has become the primary.usersregionzone 1zone 2zone 31VPC 10.0.0.0/16 spans the regionpublic 10.0.0.0/20private 10.0.128.0/20public 10.0.16.0/20private 10.0.144.0/20public 10.0.32.0/20private 10.0.160.0/202load balancer in the public subnets of every zoneappappappappappappapp SG: 8080 from LB onlyDB SG: 5432 from app only3DB primaryDB standbyreplicationobject storage: copies in every zone4zone 1 failsnow primary5A service in one region with three availability zonesA region with three zones. At the top a load balancer in the public subnets of every zone, below it two app instances in each zone. In zone 1 the database primary, in zone 2 its synchronous standby, with a replication arrow between them. Each zone lists a public and a private /20 subnet inside the VPC 10.0.0.0/16. Security groups let only the load balancer reach the app and only the app reach the database. At the bottom object storage with copies in every zone. In the last step zone 1 is crossed out and the standby in zone 2 has become the primary.usersregionzone 1zone 2zone 3110.0.0.0/20, 10.0.128.0/2010.0.16.0/20, 10.0.144.0/2010.0.32.0/20, 10.0.160.0/202load balancerappappappappappappSG: app 8080 from LB, DB 5432 from app3DB primaryDB standbyreplicationobject storage4zone 1 fails→ primary5
An availability zone is one or more data centres with independent power and network; a region is several zones a few milliseconds apart. A service survives the loss of a zone when every zone has instances, the load balancer checks their health and the data is replicated to another zone: in step 5 zone 1 disappears and zones 2 and 3 keep serving. This layout does not survive the loss of the region. The subnets are disjoint /20 blocks inside 10.0.0.0/16.
  1. A region is several zones, independent in power, cooling and network, a few milliseconds apart.
  2. The VPC spans the region; each zone has a public and a private subnet.
  3. The load balancer spreads requests over instances in every zone; security groups admit only the balancer to the app and only the app to the database.
  4. The database has a primary in one zone and a synchronous standby in another; object storage keeps copies in several zones on its own.
  5. When zone 1 fails, health checks take its instances out of rotation, the standby becomes the primary, and the other zones carry the load.

What each level protects against. Spreading instances over machines in one zone protects against a machine failure. Spreading them over zones, as in the figure, protects against the loss of a data centre. Spreading them over regions protects against the loss of a region, which is rare but has happened, through natural disasters and through failures of a region’s control plane, and it costs much more: data replicated between regions is replicated asynchronously, because a synchronous write across hundreds of kilometres would add tens of milliseconds to every commit, so a regional failover can lose the last seconds of writes. None of the three protects against a bad deploy, a deleted table, a leaked key or a provider-wide outage of a global service. Those need backups kept apart, gradual rollouts, and sometimes a second provider.

Worked example: the capacity to survive a zone. A service needs 6 instances at peak, 100 requests per second each for 600 in total. To survive the loss of one zone, the remaining zones must carry the full peak.

  • With 3 zones, the 2 that remain need 600/100/2=3600 / 100 / 2 = 3 instances each, so every zone runs 3: 9 instances, 50 % more than the 6 the load needs.
  • With 2 zones, the one that remains must carry everything: 6 per zone, 12 instances, 100 % more.

In general, with NN zones the overhead is a factor N/(N−1)N / (N - 1), which is why three zones are the common choice: the cost of tolerating a zone falls quickly from two zones to three, and slowly after that. If zone failures were independent, each with probability 0.0010.001 at a given moment, two zones down at once would have probability 0.0012=10−60.001^2 = 10^{-6}. Real failures are correlated, through shared software, a shared control plane or one bad configuration pushed everywhere, so such products are an optimistic bound, and the SLO note measures availability instead of multiplying it.

Two more reasons decide where data lives. Latency: users far from a region pay round trips, as in the networking note. Law: some countries require personal data of their residents to be stored on their territory, which fixes the region before any engineering argument starts.

Cost: on-demand, reserved, spot, and egress#

Cloud bills follow the three pricing shapes of the building blocks, plus one that surprises people.

  • On demand: pay per second for what runs, no commitment. The default, and the most expensive per hour.
  • Reserved capacity (reservations, committed-use discounts, savings plans): commit to paying for an amount of capacity for one or three years, used or not, at a discount that grows with the length of the commitment.
  • Spot (preemptible) capacity: the provider’s idle machines at a large discount, which it can take back at short notice, two minutes on AWS and 30 seconds on Google Cloud. Good for work that can be interrupted and resumed: batch jobs, CI runners, a stateless fleet that falls back to on-demand machines.
  • Egress: data leaving the provider’s network is billed per gigabyte, while incoming data is usually free; traffic between zones and between regions is billed too. A service that sends a lot of data to users, or a design that chatters across zones, can pay more for bytes than for machines.

Worked example. Toy prices: on demand d=0.10d = 0.10 dollars per hour, reserved r=0.06r = 0.06 dollars per hour for every hour of the month, spot s=0.03s = 0.03 dollars per hour, and a month of 730730 hours. An instance needed for a share uu of the month costs d⋅u⋅730d \cdot u \cdot 730 on demand and r⋅730r \cdot 730 reserved, whatever uu is. The reservation is cheaper when

r⋅730<d⋅u⋅730  ⟺  u>rd=0.060.10=0.6,r \cdot 730 < d \cdot u \cdot 730 \iff u > \frac{r}{d} = \frac{0.06}{0.10} = 0.6 ,

when the instance is needed for more than 60 % of the month, 438 hours. A full month costs $73.00 on demand, $43.80 reserved and $21.90 on spot capacity, if it is not taken back. The rule that follows: reserve the baseline that runs all the time, cover the daily peak on demand, and push interruptible work to spot.

Figure

The cost of one instance under three pricing models

Monthly cost against the share of the monthHorizontal axis: share of the month from 0 to 100 %; vertical axis: dollars per month from 0 to 80. The on-demand line rises from 0 to 73. The reservation line is flat at 43.80. The spot line rises from 0 to 21.90. The on-demand and reservation lines cross at 60 %.0204060800 %25 %50 %75 %100 %share of the month the instance is needed$break-even at 60 % (438 h)on demand, $0.10/hreserved for a year, $0.06/hspot, $0.03/hMonthly cost against the share of the monthHorizontal axis: share of the month from 0 to 100 %; vertical axis: dollars per month from 0 to 80. The on-demand line rises from 0 to 73. The reservation line is flat at 43.80. The spot line rises from 0 to 21.90. The on-demand and reservation lines cross at 60 %.0204060800 %25 %50 %75 %100 %share of the month the instance is needed$60 %on demand, $0.10/hreserved for a year, $0.06/hspot, $0.03/h
Toy prices: on demand $0.10 per hour, a one-year reservation $0.06 per hour for every hour of the month whether used or not, spot capacity $0.03 per hour while it runs; a month is 730 hours. The reservation always costs $43.80 a month, on demand $73 for a full month and proportionally less for part of one. The lines cross at the share r/d = 0.06/0.10 = 60 % of the month, 438 hours: an instance needed for longer is cheaper reserved. Spot capacity is the cheapest, but the provider can take it back at short notice, so it suits only work that can be interrupted.

Egress at a toy $0.09 per gigabyte makes 50 TB a month cost 50,000×0.09=4,50050{,}000 \times 0.09 = 4{,}500 dollars, about as much as 60 toy instances running on demand for the whole month (60×73=4,38060 \times 73 = 4{,}380 dollars). Caches near users, compression, and keeping chatty services in one zone are cost measures as much as performance measures. The tags of the previous note’s configuration are how a bill is split by service and environment, and a bill that nobody reads is the cloud’s equivalent of an unmonitored service.

The names at three providers#

Status October 2026; providers rename services often, and each has more variants than the table shows.

ConceptAWSGoogle CloudYandex Cloud
Virtual machineEC2 instanceCompute Engine VMCompute Cloud VM
Serverless containersECS on FargateCloud RunServerless Containers
Managed KubernetesEKSGKEManaged Service for Kubernetes
FunctionsLambdaCloud Run functionsCloud Functions
Block storageEBS volumesPersistent Disk, HyperdiskCompute Cloud disks
Object storageS3Cloud StorageObject Storage
File storageEFSFilestoreCompute Cloud file storage
Private networkVPC (regional)VPC (global, regional subnets)Virtual Private Cloud (cloud networks are global, subnets zonal)
Firewallsecurity groupsVPC firewall rulessecurity groups
IdentityIAM: users, roles, policiesIAM: principals, roles, service accountsIAM: accounts, roles, service accounts
Managed PostgreSQLRDS, AuroraCloud SQL, AlloyDBManaged Service for PostgreSQL
Load balancerElastic Load Balancing (ALB, NLB)Cloud Load BalancingNetwork Load Balancer, Application Load Balancer
DNSRoute 53Cloud DNSCloud DNS

The OpenTofu providers of all three expose these blocks as resources, so the configuration of the previous note works the same way for each; only the resource types and their arguments differ.

What changed#

Problem of the rented serverBlockWhat it buys
Capacity ordered weeks aheadinstances, containers and functions created by APIcapacity in seconds, billed by use
Disks die with machinesblock storage with snapshots, object storagedata that outlives machines and zones
One flat networkVPC, public and private subnets, security groupsreachability decided by rules in code
One root passwordIAM: principals, policies, short-lived credentialseach actor allowed exactly its actions
Running every service yourselfmanaged servicesthe provider patches, backs up and fails over
One data centrezones and regionsfailures contained to a zone, or a region
Paying for the peak all yearon-demand, reserved and spot capacitya bill that follows the load

Limitations#

  • The building blocks hide machines, not physics. A zone is still a building, a network link still has latency, and “unlimited” services have quotas and rate limits that appear exactly when load grows.
  • Managed services trade control for convenience: their versions, maintenance windows and failure modes are the provider’s, and moving off a proprietary service (a managed queue, a function platform, a database with extensions) is expensive. This is lock-in, and it is a business decision, not only a technical one.
  • Toy prices illustrate shapes, not amounts. Real bills have tiers, regional differences, minimum durations, charges for idle reserved addresses and storage requests, and support fees; the only reliable number is the one measured from the bill.
  • Identity policies are expressive enough to be hard to read. A set of policies that grants more than intended through a combination of statements is a common finding, and least privilege is a direction to move in, not a state that is reached once.
  • The note follows one region. Multi-region designs add replication lag, conflict resolution and global routing, and they are among the hardest problems of the field.

What you should remember#

  • Every block has three properties to choose: who operates it, where it can fail, what it costs per unit of what.
  • Compute: VMs (you run the OS), managed containers (you build the image), functions (you write the code; billed per invocation, cold starts, time limits). A function is cheaper until the load is steady enough to keep a machine busy.
  • Storage: block (a zonal disk for one machine), object (regional keys and whole objects over HTTP, very durable), file (a shared file system).
  • Networks: a VPC with public subnets for load balancers and private ones for everything else; stateful security groups that allow by port and by source group.
  • IAM: principals, policies, deny by default, explicit deny wins, short-lived credentials for machines, least privilege.
  • Shared responsibility: the provider secures the cloud, you secure what you put in it: data, identities, rules and your own software.
  • Zones contain data-centre failures, regions contain regional ones, and neither contains your own mistakes. Surviving one zone of NN costs a factor N/(N−1)N/(N-1) in capacity.
  • Cost: reserve the baseline when it runs more than r/dr/d of the time, buy the peak on demand, run interruptible work on spot, and watch egress.

Example#

The network of the figure, as an OpenTofu configuration for AWS (provider 6.x): a VPC, a public and a private subnet in each of three zones, and the three security groups of the table. It was written against the provider’s documentation and not executed here. A complete network also needs an internet gateway, route tables and a NAT gateway, left out to keep the file short.

variable "zones" {
  type    = list(string)
  default = ["eu-central-1a", "eu-central-1b", "eu-central-1c"]
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
  tags       = { Name = "web" }
}

resource "aws_subnet" "public" {
  count             = length(var.zones)
  vpc_id            = aws_vpc.main.id
  availability_zone = var.zones[count.index]
  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 4, count.index)
}

resource "aws_subnet" "private" {
  count             = length(var.zones)
  vpc_id            = aws_vpc.main.id
  availability_zone = var.zones[count.index]
  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 4, 8 + count.index)
}

resource "aws_security_group" "lb" {
  name   = "web-lb"
  vpc_id = aws_vpc.main.id
}

resource "aws_security_group" "app" {
  name   = "web-app"
  vpc_id = aws_vpc.main.id
}

resource "aws_security_group" "db" {
  name   = "web-db"
  vpc_id = aws_vpc.main.id
}

resource "aws_vpc_security_group_ingress_rule" "lb_https" {
  security_group_id = aws_security_group.lb.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

resource "aws_vpc_security_group_egress_rule" "lb_to_app" {
  security_group_id            = aws_security_group.lb.id
  referenced_security_group_id = aws_security_group.app.id
  ip_protocol                  = "tcp"
  from_port                    = 8080
  to_port                      = 8080
}

resource "aws_vpc_security_group_ingress_rule" "app_from_lb" {
  security_group_id            = aws_security_group.app.id
  referenced_security_group_id = aws_security_group.lb.id
  ip_protocol                  = "tcp"
  from_port                    = 8080
  to_port                      = 8080
}

resource "aws_vpc_security_group_egress_rule" "app_to_db" {
  security_group_id            = aws_security_group.app.id
  referenced_security_group_id = aws_security_group.db.id
  ip_protocol                  = "tcp"
  from_port                    = 5432
  to_port                      = 5432
}

resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
  security_group_id            = aws_security_group.db.id
  referenced_security_group_id = aws_security_group.app.id
  ip_protocol                  = "tcp"
  from_port                    = 5432
  to_port                      = 5432
}
  • variable "zones" lists three zones of the Frankfurt region; another region, or another provider, changes only this list and the resource types.
  • aws_vpc.main reserves 10.0.0.0/16. The Name tag is what the console shows.
  • aws_subnet.public uses count: one resource block makes three subnets, addressed aws_subnet.public[0] to [2], each in the zone var.zones[count.index].
  • cidrsubnet(prefix, newbits, netnum) computes a subnet: it extends the prefix by newbits bits and picks block number netnum. With 4 extra bits a /16 becomes /20 blocks, and blocks 0, 1, 2 are 10.0.0.0/20, 10.0.16.0/20 and 10.0.32.0/20: the plan of the worked example, computed by the tool instead of written by hand.
  • aws_subnet.private takes blocks 8, 9 and 10, which start at 10.0.128.0, the upper half of the range.
  • The three aws_security_group resources are empty containers for rules. The provider deletes the allow-all outgoing rule that AWS adds to a new group, so a group created this way allows nothing in either direction until a rule says so.
  • lb_https admits TCP 443 from anywhere into the balancer’s group: the only rule that mentions the internet.
  • lb_to_app and app_from_lb are the two halves of one permission: the balancer may open connections to port 8080 of members of app, and members of app accept them from members of lb. referenced_security_group_id names a group instead of addresses.
  • app_to_db and db_from_app do the same for PostgreSQL on 5432. Nothing admits connections to the database from anything else, and since the groups are stateful, no rules are needed for the replies.
  • Each rule is its own resource with its own address, so a plan that adds or removes one rule shows exactly that one line, which is what a reviewer of a security change wants to see.

Next#

The building blocks run single containers, single machines, and groups of identical machines. A service of many components, each with several copies that must be placed on machines, restarted when they fail, connected to each other and replaced one by one during a deploy, needs something that does this continuously. The next note introduces Kubernetes, which applies the reconciliation of the infrastructure-as-code note, desired state against actual state, in a loop that never stops.

References#