Back to Terraform

Capstone B: Release a Versioned, Tested Web-Service Module

November 6, 2026 Wasil Zafar 45 min read

Build a reusable service module with contract tests, one real integration test and an availability rehearsal

Table of Contents

  1. Specify the Service Contract and Availability Target
  2. Compose Network, Compute and Load-Balancing Capabilities
  3. Publish a Pinned Module Release and Consumer Example
  4. Test Bad Inputs, Planned Shape and Real Readiness
  5. Measure an Upgrade and Document the Recovery Route
  6. Submit a Consumer-Ready Release Bundle

Specify the Service Contract and Availability Target

A capstone is graded by what a reviewer can reject. You will publish one versioned module, prove three different claims with three different instruments, rehearse one replacement under a stopwatch, and hand over a bundle a consumer can use without asking you a question. The infrastructure is deliberately dull: a stateless HTTP service behind one load balancer. The evidence is the work.

The service answers two questions about itself. A liveness path reports that the process is running; a readiness path reports that the instance can actually serve traffic. The module owns everything between an injected network and those two answers, and nothing above them. That narrow sentence is the whole contract, and every later decision has to fit inside it.

Three groups read the contract for different reasons. Application teams call the module, clients call the endpoint, and the on-call engineer reads the availability target when a page arrives. The module serves all three only if the interface and the target are written down separately.

Six deliverables are the submission. Each one is a file a reviewer reads, not a task you remember doing.

#DeliverableAccepted when
D1Contract and availability recordOne page names users, inputs, outputs, boundary, SLO, error budget, RTO and non-goals
D2Composition and ownership mapEvery object has one owner and one layer; injected values are named
D3Pinned releaseAnnotated tag, changelog, two examples and a consumer call with a version pin
D4Test evidenceBad-input, planned-shape and readiness results saved in one report
D5Upgrade measurementBaseline, change window and after-state, each with a timestamp and a gate
D6Recovery routeOrdered rollback steps, decision owner and a verified return to green

Five inputs describe the service, and one of them is the network. The split matters more than the count, because a value that belongs to another owner must be injected rather than discovered.

InputThe caller decidesThe module decides
servicename, release, port, health and readiness paths, capacity floorname suffix, tag merge, health-check timing
networkVPC id, two public subnets, two private subnetssecurity-group rules derived from that boundary
listenerprotocol, port, certificate ARN when TLS terminates heredefault action and target-group wiring
computeAMI id, instance type, user datalaunch-template shape and group defaults
tagsowner, cost centre, data classmanaged-by marker and applied release

Outputs use the consumer's vocabulary, not the provider's. Four values cover every integration the module promises, and a fifth reports what was actually released so a caller can prove the running fleet matches the pinned tag.

OutputConsumer use
endpointhost name to place in a DNS record owned elsewhere
target_group_arnattach a WAF, a second listener or a canary rule
autoscaling_group_namestart or inspect an instance refresh from the consumer's pipeline
security_group_idsadd a peered network's rule without editing the module
releaseecho of the applied release label, for drift and audit evidence

The network boundary is two lines, and both are testable. The load balancer sits in public subnets and accepts only the caller's allowed CIDR; instances sit in private subnets, hold no public address, and accept traffic only from the load balancer's security group. Egress to a package mirror crosses the caller's NAT gateway. The module never creates a VPC, a NAT gateway, a DNS record or a certificate.

Availability has to be defined at the seam the module controls. A module cannot promise that an application returns the right answer; it can promise that at least the desired count stays healthy across two zones while the platform is behaving.

ObjectiveMeasureTargetEvidence
Endpoint availabilityexternal probe, one request per second99.5% of a 30-day monthD5 probe summary
Error budgetfailed probes over total probesabout 3.6 hours per monthD1 and D5
Healthy capacitytargets healthy in the target groupat least the desired count across two zonesD4 readiness run
Planned replacementrequests failing because a target was replacedzero while the floor is respectedD5 change window
Recoveryminutes from stop decision to both routes green15 minutesD6 rehearsal

Two targets, two different clocks. The monthly availability figure is an operations promise measured after the fact; the change gate is a per-release rule that stops a rehearsal the moment the error rate moves. Confusing the two produces either a frozen platform or a quiet outage, so write both into D1 with distinct owners.

An error budget is only useful with a stop rule attached. At 99.5%, the budget is roughly three and a half hours a month. Spend it deliberately on releases, and stop changing when half is gone unless the change is the fix. That rule is a sentence in D1, not a dashboard someone has to interpret at two in the morning.

The acceptable disruption is stated per action, not per service. This is the table a reviewer checks before approving the rehearsal.

ActionAllowed customer impactGate that enforces it
Rolling replacementno increase in 5xx above baselineminimum healthy percentage and probe loop
Listener or certificate changea brief TLS handshake failure is not acceptablechange in a maintenance window with a canary target
Scale-outnonecapacity floor verified before the change
Scale-innone while the floor holdsdesired count never below two
Destructive changenever during the rehearsalplan review stops the run

Non-goals are part of the contract because they prevent a fork. The module does not create DNS records, request certificates, attach WAF rules, package the application artifact or manage the VPC. A consumer who needs those things composes them beside the module, which keeps the module small and the ownership map honest.

Figure 1 is the order a reviewer checks the contract: users, interface, boundary, then a target that can be measured. Figure 2 turns the same page into the boundary a caller sees, with the target beside it.

Specify the Service Contract and Availability Target
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    U["Callers: jobs, partners, browsers"] --> C{"Does the contract
fit on one page?"} C -- "no" --> X1["Split the capability or
move a decision to the caller"] C -- "yes" --> I["Inputs: service, network,
listener, compute, tags"] I --> O["Outputs: endpoint, target group,
group name, release"] O --> N{"Is the boundary explicit?
public edge, private compute"} N -- "no" --> X2["Hidden dependency:
VPC, DNS or certificate"] N -- "yes" --> A{"Is the target measurable
where the module runs?"} A -- "no" --> X3["99.5% of what,
measured from where?"] A -- "yes" --> T["SLO, error budget,
RTO and stop rules"] T --> R["Release plan: D1 and D3"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class U,C,N,A primary; class I,O,T secondary; class R ok; class X1,X2,X3 danger;
Four contract decisions and one measurable availability target Callers reach a module contract that fixes inputs, outputs, a network boundary and the acceptable disruption. To the right, the availability target records endpoint availability, error budget, healthy capacity across two zones and a fifteen-minute recovery time. One page, four boundaries, one target If a reviewer cannot restate a row, the contract is not finished. Callers internal jobs partner webhooks module contract 1. inputs service, network, listener, compute, tags 2. outputs endpoint, target group, group name, release 3. network boundary public edge, private compute, injected VPC 4. acceptable disruption zero replacement failures at the floor 99.5% monthly about 3.6 h of budget two zones healthy at or above the floor replacement gate no 5xx above baseline 15-minute recovery pin back, apply, verify The monthly target and the per-change gate are different clocks with different owners.

Compose Network, Compute and Load-Balancing Capabilities

Composition is three layers and no fourth. A consumer root configures the provider, the backend and the pin. The service module holds the capability and its decisions. Provider resources sit underneath. A network team's outputs enter as ordinary values, not as a module the service calls.

Inject the network; never discover it. A module that reads remote state has an invisible dependency at every call site and cannot be tested without the producer's state. The network object carries exactly three identifiers: one VPC and two subnet lists. Everything else about the network belongs to the team that owns it.

A shallow module is one decision deep. Wrapping a single security group in its own module adds a variable file, an output and a README without removing any decision from the caller. The service module earns its boundary because it decides the relationship between the edge, the target group and the instance fleet.

CapabilityOwnerHow it crosses the module boundary
VPC, subnets, route tables, NATnetwork teamVPC and subnet ids in network; routes and NAT stay there
Load balancer, listener, target groupservice modulecreated per module call
Edge and instance security groupsservice modulederived from the listener and the network
AMI, instance type, boot scriptconsumercompute object
DNS record and certificateconsumercreated outside, certificate ARN passed in
Provider configuration, region, stateconsumer rootinherited by the module

One module call is one service, and one root is one environment. Environments differ by backend key and account, not by a copy of the module. A module per environment forks the configuration and guarantees that a fix lands twice or once, depending on who remembered.

Instances are counted by the group, not by the module. There is no instance_count input: the service module owns one autoscaling group per call, and the caller owns its floor and ceiling. Nested counts would move the resource address for no operational gain and make the replacement rehearsal ambiguous.

Validation belongs at the seam, where the message can still help. Cheap shape rules run as variable validations. Rules that need provider reads, such as distinct availability zones, run as preconditions on the load balancer so the failure names the object that needed the fact.

RuleMechanismMessage tells the caller
at least two subnets per listvariable validationadd a subnet so the edge can span zones
floor between two and the ceilingvariable validationcapacity below two cannot survive a replacement
HTTPS listener requires a certificatevariable validationpass an ACM ARN or choose HTTP for the lab
health paths start with a slashvariable validationuse an absolute path such as /readyz
subnets span at least two zonesprecondition with a subnet data sourcethe supplied ids are all in one zone

One rule is deliberately not a mock test. The distinct-zone precondition needs real subnet data, so the contract suite either supplies mocked zones or leaves that check to the integration fixture, where the provider answers with actual availability zones. A mock that invents a single zone would fail a correct configuration, which teaches the wrong lesson.

The boot script is injected, not generated. The module does not know how to install the application, and pretending otherwise would tie a reusable capability to one codebase. The consumer passes an AMI and user data; the module guarantees the health check, the security boundary and the replacement mechanics around them. The launch template also requires instance metadata v2 and encrypts the root volume, because both are defaults a caller should not have to remember.

Three edge defaults are contract decisions, not provider trivia. Cross-zone balancing keeps both zones serving when one is degraded, invalid-header dropping keeps malformed requests away from the application, and a bounded idle timeout limits how long a drained target holds a silent connection. Set them in the module, document them in the README, and test the settings that change behaviour.

Two failure modes dominate this composition. A single-zone subnet list produces a load balancer that cannot meet its own availability promise, and a readiness path that answers before dependencies are up produces a target group that reports healthy while returning errors.

Non-goalWhy it stays outside
DNS recordthe zone belongs to the consumer and may be shared
Certificate issuance and validationapproval and renewal are separate ownership
WAF and rate limitingpolicy differs per consumer and per route
Application packagingthe module must serve more than one codebase
VPC and NATnetwork ownership predates the service

Figure 3 draws the composition: the root and the network owner feed values across a dashed boundary, and the module owns only the resources that implement the capability. Figure 4 is the mechanics, with the two failure branches a reviewer should ask about.

A service module composed from injected network values and owned edge resources The consumer root supplies provider configuration, state and a pinned version. The network owner supplies a VPC and public and private subnets. Inside the dashed module boundary, security groups, a load balancer and listener, a target group and an autoscaling group are created. DNS, certificates, WAF and application packaging stay outside as documented non-goals. Values in, capability out The module never reads state and never configures a provider. consumer root provider, region, state module pin v1.3.0 desired floor and ceiling network owner one VPC two public subnets two private subnets NAT for egress capability boundary: service security groups edge accepts the allowed CIDR load balancer and listener public subnets, default action target group and health check readiness path, draining delay launch template and group private subnets, pinned release outputs endpoint, target group, group name, release stays outside DNS record certificate issuance WAF and rate limits application artifact VPC and NAT rehearsal gate floor held, probe clean One layer adds one decision: the root wires, the module decides, the provider performs.
Compose Network, Compute and Load-Balancing Capabilities
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    R["Root: provider, state,
network ids injected"] --> V{"Subnets in at least
two availability zones?"} V -- "no" --> E1["Single-zone service
availability target unreachable"] V -- "yes" --> S["Security groups
edge and instance"] S --> L["Load balancer and listener
in public subnets"] L --> T["Target group
health check on readiness path"] T --> G["Autoscaling group
private subnets, pinned release"] G --> H{"Targets report
healthy?"} H -- "no" --> E2["503 at the listener
readiness or port wrong"] H -- "yes" --> OK["Endpoint serves traffic
ready for the integration test"] G -- "quota or launch failure" --> E3["No healthy target
capacity never reaches floor"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class R,V,S,L,T,G,H primary; class OK ok; class E1,E2,E3 danger;

Publish a Pinned Module Release and Consumer Example

A release is a tag plus a promise about what will not change. The tag is the pin; the changelog is the promise. Consumers never track a branch, and a merge to the default branch is not a release, because a moving ref makes yesterday's plan unreproducible.

Semantic versioning works only when breaking is defined by the caller's diff. An internal refactor with moved blocks is a patch for the consumer. A new optional input is a minor. A renamed output, a changed default that alters planned resources, or a raised provider floor is a major.

ChangeVersionConsumer action
bug fix, same planned shapepatchmove the pin when convenient
new optional input or new outputminornone
internal address change with moved blockspatch or minornone; state is rewritten on apply
changed default that alters resourcesmajorread the changelog, expect a plan
renamed or removed input or outputmajoredit the call in the same change
raised Terraform or provider floormajorupgrade the root and re-init

The module declares ranges; the consumer pins points. Inside the module, the CLI floor accepts 1.17 and later, and the provider range stops before the next major. In the consumer root, CI pins the exact Terraform and provider versions, and the lock file records the selection. Ranges keep the module usable; points make the build reproducible.

The repository layout is part of the contract. A consumer should find the interface, the examples and the evidence without reading the resource files.

PathPurposeChecked by
modules/service/versions.tfCLI floor and provider rangeterraform init and review
modules/service/variables.tffive inputs and their rulesplan tests and negative runs
modules/service/main.tfsecurity groups, edge, target group, groupplan assertions
modules/service/outputs.tffive consumer-facing valuesplan assertions
README.mdcapability, tables, non-goals, destroy behaviourgenerated-table check
CHANGELOG.mdevery version, with the breaking line firstrelease review
examples/basicsmallest legal callinit, validate, plan in CI
examples/completeTLS listener, tags, capacity rangeplan in CI
tests/plan.tftest.hclbad inputs and planned shapeevery pull request
tests/readiness.tftest.hclone real apply and proberelease branch, disposable account

The consumer call is ordinary wiring with one interesting line. The double slash selects the module directory inside the repository, and the ref selects the release. Nothing else in the call refers to a branch, a commit hash or a local path.

module "orders" {
  source = "git::ssh://git@example.com/platform/terraform-modules.git//modules/service?ref=v1.3.0"

  service = {
    name        = "orders-api"
    release     = "2026-11-06"
    port        = 8080
    health_path = "/healthz"
    ready_path  = "/readyz"
    min_size    = 2
    max_size    = 8
    desired     = 4
  }

  network = {
    vpc_id             = module.network.vpc_id
    public_subnet_ids  = module.network.public_subnet_ids
    private_subnet_ids = module.network.private_subnet_ids
  }

  listener = {
    protocol        = "HTTPS"
    port            = 443
    certificate_arn = aws_acm_certificate_validation.api.certificate_arn
  }

  compute = {
    ami_id        = data.aws_ami.service.id
    instance_type = "t3.micro"
    user_data     = filebase64("${path.module}/bootstrap.sh")
  }

  tags = {
    owner       = "payments"
    cost-centre = "orders"
    data-class  = "internal"
  }
}

The changelog is the upgrade path, not a list of commits. Each entry leads with the consumer-visible change and the action it requires, so a reader can decide whether to move the pin before reading the diff.

VersionConsumer-visible changeAction
v1.3.0readiness path is a separate inputadd ready_path, or accept the default
v1.2.0replacement uses a rolling refreshnone; review the capacity floor
v1.1.0release output echoes the applied labelnone
v1.0.0first stable contractpin it and run both examples

Deprecation is a warning at the call site plus a documented window. Mark the old input as deprecated so the consumer's plan names the replacement, keep it for one major release, and map it to the new attribute inside the module. Then remove it in the next major and say so in the changelog first.

Two examples are the minimum proof that the interface is usable. The basic example is the smallest legal call and runs on every pull request. The complete example exercises TLS, a certificate ARN, a wider capacity range and an extra tag; if it needs a value the interface cannot express, the interface is wrong.

Ownership is drawn, not assumed. The module team owns the tag, the changelog and the default health-check behaviour. The consumer owns the network values, the certificate, the AMI, the boot script and the decision to move the pin. The network team owns everything below the identifiers.

Figure 5 shows the release path and the ownership split. The crimson branch is the one to remove: a consumer that pins a branch has no release at all.

A tagged module release pinned by a consumer, with ownership split The module repository holds a tag, a changelog, two examples and a test suite. The consumer pins the tag in the source reference and records provider versions in the lock file. A branch reference is rejected because it moves. The bottom band assigns ownership to the module team, the consumer and the network team. A tag is the only thing a consumer should follow module repository tag v1.3.0 annotated, immutable CHANGELOG: breaking line first action per version examples/basic and complete each one a root module tests: plan and readiness results attached to the tag The tag names the whole tree. pin ?ref=v1.3.0 never a branch provider point aws 6.72.0 in lock main branch moves under the caller consumer root Terraform 1.17.1 required_version in CI image module call five inputs, one source pin lock file and plan digest reviewable, reproducible outputs feed DNS and WAF owned by the consumer module team: tag, changelog, defaults, test results consumer: network values, certificate, AMI, boot script, pin movement. network team: everything below the identifiers.

Test Bad Inputs, Planned Shape and Real Readiness

Three instruments answer three different questions, and none of them substitutes for another. Validation asks whether the call is well formed. A plan test asks whether the module wires the right shape. An apply with a probe asks whether the running service actually answers. A release bundle needs all three, labelled with the claim each one makes.

TierInstrumentClaim it earnsCostIt cannot prove
Staticformat check and validationfiles parse and arguments match the provider schemaseconds, no accountcredentials, quota, naming, behaviour
Contractplan tests with a mock providerinputs, defaults, rules and planned shape agreeseconds, no accountthe provider accepts the calls
Integrationapply plus an HTTP probethe fleet boots and both routes answer through the load balancerminutes, disposable accountload behaviour, long-run stability

Bad inputs are the cheapest test and the easiest to skip. Every validation deserves at least one run that expects the named variable to fail, because a rule with no test disappears in a refactor without anyone noticing. Test the boundary and one plausible mistake per rule, not a single obviously wrong string.

MutationExpected failing objectWhy it matters
one private subnetvar.networkthe fleet cannot survive a zone loss
floor of one instancevar.servicereplacement would drop below the availability promise
HTTPS without a certificatevar.listenerthe listener would fail at apply, not at review
readiness path without a leading slashvar.servicethe health check silently targets the wrong URI
a name with an underscorevar.serviceload-balancer and group names reject it
ceiling below the floorvar.servicecapacity arithmetic is invalid before any resource exists

The plan suite keeps the positive and negative runs in one file, separated by name. One positive run asserts the shape, and the negative runs each expect exactly one object to fail. A run that expects a failure must not assert values computed after the failure, so keep the expected-failure runs narrow.

# tests/plan.tftest.hcl
mock_provider "aws" {}

variables {
  service = {
    name = "orders-api", release = "2026-11-06", port = 8080
    health_path = "/healthz", ready_path = "/readyz"
    min_size = 2, max_size = 6, desired = 2
  }
  network = {
    vpc_id             = "vpc-0123456789abcdef0"
    public_subnet_ids  = ["subnet-0aaa", "subnet-0bbb"]
    private_subnet_ids = ["subnet-0ccc", "subnet-0ddd"]
  }
  listener = { protocol = "HTTP", port = 80, certificate_arn = null }
  compute  = { ami_id = "ami-0123456789abcdef0", instance_type = "t3.micro" }
  tags     = { owner = "payments" }
}

run "plan_holds_the_shape" {
  command = plan

  assert {
    condition     = aws_lb_target_group.this.port == var.service.port
    error_message = "The target group must listen on service.port; the listener forwards to it."
  }
  assert {
    condition     = aws_lb_target_group.this.health_check[0].path == var.service.ready_path
    error_message = "The health check must use the readiness path, not the liveness path."
  }
  assert {
    condition     = aws_autoscaling_group.this.min_size >= 2
    error_message = "A floor below two cannot survive a replacement in two zones."
  }
  assert {
    condition     = aws_lb_listener.this.default_action[0].type == "forward"
    error_message = "The listener must forward to the target group; a fixed response hides a broken fleet."
  }
}

run "plan_rejects_one_subnet" {
  command = plan
  variables {
    network = {
      vpc_id             = "vpc-0123456789abcdef0"
      public_subnet_ids  = ["subnet-0aaa", "subnet-0bbb"]
      private_subnet_ids = ["subnet-0ccc"]
    }
  }
  expect_failures = [var.network]
}

run "plan_rejects_https_without_a_certificate" {
  command = plan
  variables {
    listener = { protocol = "HTTPS", port = 443, certificate_arn = null }
  }
  expect_failures = [var.listener]
}

Assert planned configuration, never provider-assigned identifiers. The target group's ARN, the load balancer's DNS name and the instance ids are unknown during a plan, so a condition that compares them either fails or asserts a mock's invented value. Assert the port, the paths, the counts, the tags and the default action; those are the values the module actually decides.

A mock provider is honest about one thing: it invents every response. Use it to keep the contract suite fast and credential-free on every pull request. Do not read its green result as evidence that AWS accepts the arguments, that IAM allows the call, that the names are free or that a target ever becomes healthy.

Mock-backed plan provesOnly an apply can prove
defaults fill omitted optional attributesthe provider accepts the call and the values are legal
validation and expect_failures firethe caller's role has the write grants
names, tags and counts derive correctlythe name is unique in the account and region
listener, target group and group are wiredquota allows the fleet and the rules permit traffic

Readiness needs a real HTTP client, not another assertion on a plan value. The integration fixture calls the module, then runs a bounded probe against both routes through the load-balancer DNS name. The probe is ordinary configuration with a documented cost: it makes the apply fail when the service never becomes ready.

# tests/fixtures/readiness/main.tf
module "service" {
  source = "../../../modules/service"
  # the five inputs from the consumer example in the release section
}

resource "terraform_data" "probe" {
  triggers_replace = [module.service.endpoint, module.service.release]

  provisioner "local-exec" {
    interpreter = ["/bin/bash", "-c"]
    command     = <<-EOT
      set -euo pipefail
      for attempt in $(seq 1 40); do
        if curl -fsS --max-time 5 "http://${module.service.endpoint}/healthz" \
          && curl -fsS --max-time 5 "http://${module.service.endpoint}/readyz"; then
          exit 0
        fi
        sleep 15
      done
      echo "readiness did not arrive within ten minutes" >&2
      exit 1
    EOT
  }
}

The suite points one run at the fixture, so a probe that never turns green fails the apply and the test together. The assertion only records the release label; the probe is the evidence that both routes answer.

# tests/readiness.tftest.hcl
run "readiness_answers_through_the_edge" {
  command = apply

  module {
    source = "./fixtures/readiness"
  }

  assert {
    condition     = output.release != ""
    error_message = "The module must echo the release it applied; the probe has already proven both routes."
  }
}

The two routes fail for different reasons, which is why both are probed. A liveness failure means the process never started: wrong user data, wrong port, a missing package. A readiness failure means the process is up but a dependency is not reachable: the security group, the subnet route or the package mirror. Reporting only one of them sends the next engineer to the wrong layer.

Warmup makes a green probe early evidence of nothing. A target group registers an instance before the application has finished booting, so the probe loop must tolerate the gap and the health check must use the readiness path. If the check uses the liveness path, the load balancer sends traffic to an instance that is not ready yet, which is the exact failure the rehearsal is meant to catch.

Delete the probe or keep it, but decide. In a release rehearsal the probe is evidence; in a long-lived consumer root it is a cost and a source of flakiness. Keep it in the test fixture, run it on the release branch, and let the consumer's own monitoring own readiness afterwards.

Measure an Upgrade and Document the Recovery Route

An upgrade is a measurement with a start time and a decision, not an apply that exited zero. The rehearsal changes one input — the release label, and through it the launch template — then watches availability, error rate and healthy capacity until the fleet settles or the gate closes.

Only one thing should change. The release input reaches the launch template and triggers an instance refresh. The target group, listener, security groups and addresses stay identical. If the plan shows a replacement of the listener, the target group or the autoscaling group, stop: the change has crossed a boundary it was not supposed to touch.

The capacity floor is what makes the replacement boring. A minimum healthy percentage of 100 keeps the desired count serving while instances are replaced. The module accepts a floor of two, but the rehearsal runs at four — two per zone — so a replacement never leaves a zone with a single target.

SettingRehearsal valueWhy it is the value
minimum healthy percentage100replacement must not reduce serving capacity
instance warmup120 secondsthe application needs time before it counts as healthy
deregistration delay30 seconds in the lab, 300 in productionin-flight requests finish before the target leaves
health check interval15 secondsfast enough to catch a bad instance in the window
unhealthy threshold3tolerates one transient failure without flapping
desired capacity4 across two zonestwo per zone leaves room for one replacement each

Five signals decide whether the change is acceptable. Record each one at baseline, during the window and after steady state; a value without a timestamp is an opinion.

SignalInstrumentGate
Availabilityexternal probe, one request per secondno failed probe attributable to replacement
Server errorsload-balancer 5xx metric and probe status codesno increase above baseline
Latencyprobe p95 over five-minute bucketsinside the service's own target
Healthy capacitytarget group healthy count and zone spreadat or above the floor throughout
Refresh progressinstance refresh status and timestampsreaches successful, or the run stops

The probe loop is what turns the gate into a timestamp. Run it from outside the VPC, at one request per second, for five minutes before the change, through the replacement, and for five minutes after. Log the timestamp, status code and latency of every request; the first failure and the last failure are the two numbers the report needs.

A baseline that is already noisy cancels the rehearsal. If the pre-change window shows failures, the measurement cannot attribute anything to the release. Fix the baseline or move the window; do not proceed and explain the noise afterwards.

Draining is a promise to in-flight requests, not a pause. The load balancer stops sending new requests when a target leaves, then waits for existing connections to finish. If the application's longest request exceeds the deregistration delay, requests fail during a replacement even though every health check passed.

Data compatibility decides whether rollback is possible at all. This service is stateless: no schema, no session affinity, no local writes that matter. That is what makes a fifteen-minute rollback credible. If a future version adds a migration, the recovery route needs a snapshot step and the RTO becomes a data decision rather than a template decision.

The recovery route is one input and one apply. It is short because the release is pinned, and it is rehearsed because an unrehearsed rollback is a hope. Rehearse it after a clean upgrade, not only after a failure, so the first real use is not the first real attempt.

  1. Detect. The probe or the 5xx metric crosses the gate; record the timestamp and the failing signal.
  2. Freeze. Stop further applies and stop the rollout if it is still running; the old capacity keeps serving.
  3. Decide. Roll back unless a forward fix is already written, reviewed and smaller than the rollback.
  4. Revert one line. Set the module pin back to the previous tag in the consumer root.
  5. Apply the reverted root. The launch template returns to the previous release and a new refresh begins.
  6. Verify both routes. Probe liveness and readiness, confirm the healthy count and the zone spread.
  7. Record. Write the detection time, the decision, the recovery time and the follow-up into D6.

The rollback target must still exist. A tag can be deleted and an image can be overwritten, and either turns a fifteen-minute recovery into an archaeology project. Keep the previous two releases published, keep their images addressable, and say so in the changelog.

Figure 6 puts the two outcomes side by side: a clean refresh that never drops below the floor, and a failed readiness check that returns to the previous pin. Figure 7 is the evidence flow, including the branch where the recovery misses its own target.

A rolling replacement that succeeds and a readiness failure that rolls back The v1.3.0 fleet serves four instances across two zones. An instance refresh with a hundred percent healthy floor moves the fleet to v1.4.0 while the probe measures availability. If readiness fails or the error gate opens, the consumer reverts the version pin, applies, and returns to v1.3.0 inside a fifteen-minute recovery target. One input changes, capacity does not v1.3.0 baseline zone a zone a zone b zone b floor: four serving probe: five-minute baseline instance refresh healthy floor 100% warmup 120 s drain 30 s in the lab one instance per zone old capacity serves until the new target passes v1.4.0 steady state zone a, new release zone a, new release zone b, new release zone b, new release floor: four serving probe: five-minute after gate opens: readiness fails or 5xx rises freeze applies, keep the old capacity serving recovery: pin back to v1.3.0 apply the consumer root, then refresh again both routes green inside 15 minutes record detection, decision, recovery timestamps keep the previous two tags and images published data migrations turn recovery into a data decision A rollback is a release too: it needs a pin that still exists and a rehearsal that was measured.
Measure an Upgrade and Document the Recovery Route
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    B["Baseline probe, five minutes
record availability, 5xx, p95"] --> A["Apply the pinned v1.4.0
release input changes"] A --> R["Instance refresh
floor 100 percent"] R --> P{"During the window:
failed probe or 5xx rise?"} P -- "no" --> S{"Steady state:
floor healthy in two zones?"} S -- "yes" --> OK["Accept: close D5 with
baseline and after timestamps"] S -- "no" --> F["Freeze applies
old capacity keeps serving"] P -- "yes" --> F F --> D{"Rollback can finish
inside 15 minutes?"} D -- "yes" --> RB["Revert the pin, apply,
probe both routes"] D -- "no" --> INC["Declare the incident,
escalate, add capacity"] RB --> G{"Both routes green
and floor restored?"} G -- "yes" --> OK2["Record recovery timestamp
and open the follow-up"] G -- "no" --> INC classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class B,A,R,P,S,D,G primary; class F warn; class OK,OK2,RB ok; class INC danger;

Submit a Consumer-Ready Release Bundle

A bundle is accepted when someone else can replay it without you. That means the tag, the changelog, the examples, the test report, the measurement and the recovery route are all present, and each one names the claim it supports. A folder of screenshots is not a bundle.

DeliverableArtifactReviewer's question
D1contract and availability recordcan I restate the SLO, the boundary and the stop rule?
D2composition and ownership mapdoes every object have exactly one owner?
D3tag, changelog and two examplescan I call the module from the changelog alone?
D4test report with three tierswhich claim does each green result actually support?
D5measurement table with timestampswas the gate held, and where is the evidence?
D6recovery route and rehearsal loghow long did the return to green take?

The release is reproducible from three pinned values plus one reviewed digest. The module tag, the Terraform version and the provider version together determine the configuration and the lock file. Record all three in the bundle, and record the plan digest that was reviewed, so a later reviewer can tell whether the applied plan is the approved one.

The test report separates claims on purpose. One section holds the plan suite with its negative runs; another holds the apply run with the probe output. A reader who cannot see which suite produced a green line will over-trust it, and the first production failure will be blamed on the tests rather than on the gap between them.

Cleanup is part of the handover, not an afterthought. The rehearsal creates a load balancer, an autoscaling group and its instances, and the integration run creates the same set in the disposable account. Destroy the fixture first, then the rehearsal root, then confirm the tag-based inventory is empty. The consumer keeps the module; the author keeps no cloud resources.

The review below is the capstone in one pass. It assumes the disposable account, the pinned versions and the two roots already exist; the point is the order and the evidence, not another build.

Capstone

Module release acceptance review

Status: design-only. No AWS account was used to produce this capstone, and these steps were not executed here. Versions: Terraform CLI 1.17.1, hashicorp/aws 6.72.0, verified 6 November 2026. The rehearsal account must be disposable, and the network identifiers must come from a sandbox VPC you own.

Prerequisites. A sandbox account and one region, a VPC with two public and two private subnets and a NAT route for egress, an ACM certificate only if you rehearse the HTTPS listener, an AMI with a boot script that serves /healthz and /readyz, and permission to manage load balancers, autoscaling groups, security groups and EC2 instances. Keep the account id and certificate ARN in the environment, never in the module.

Bundle checklist. Attach D1 to D6, the annotated tag, the changelog, the plan digest, the test report and the recovery log. The review is not complete until every row below has an artifact behind it.

StageActionPass condition
Contractread D1 aloud and restate the SLO and the stop ruleboth are measurable and owned
Composetrace every input to its ownerno value is discovered inside the module
Releasecheck the tag, changelog and both examplesthe consumer call needs nothing outside the page
Inputsrun the plan suite with its negative caseseach rule fails the named object, one at a time
Shaperead the positive assertionsport, paths, floor, tags and default action are asserted
Readinessapply the fixture and run the probeboth routes answer through the load-balancer name
Baselineprobe for five minutes before the changeno failures, latency recorded
Upgradechange the release input and applyrefresh starts, floor holds, no listener replacement
Measureread availability, 5xx, p95 and healthy countevery gate holds, timestamps recorded
Recoverrevert the pin, apply, probe both routesgreen inside fifteen minutes, log complete
Cleandestroy the fixture and the rehearsal roottag-based inventory returns nothing
  1. Freeze the versions. Record Terraform 1.17.1, hashicorp/aws 6.72.0 and the module tag in D3 before the first command. A rehearsal that starts on a different provider cannot be compared with the release.
  2. Validate the contract on paper. Walk D1 row by row with the reviewer. Stop if the availability target cannot be measured from outside the VPC, or if a non-goal has crept into the input list.
  3. Run the static gates. Format check, validate and a plan of both examples in the module repository. Expect no provider write and no unexpected replacement in the examples.
  4. Run the contract suite. Execute the plan tests, then remove one validation block in a scratch copy and re-run. The matching negative run must fail because the expected failure never arrived; that is the test proving it tests the rule.
  5. Apply the readiness fixture. Use the disposable account, a prefix that identifies the run and a short lifetime. Expect a load balancer, a group at the rehearsal floor and four healthy targets, two per zone, with both routes answering.
  6. Record the baseline. Run the external probe for five minutes at one request per second. Save the status distribution, the p95 and the healthy count; a noisy baseline cancels the rehearsal.
  7. Change one input. Set the release label to the new build and apply the consumer root. Confirm in the plan that the listener, target group and security groups are unchanged and that the launch template moves.
  8. Watch the refresh. Keep the probe running through the window. Record the first timestamp at which a new target becomes healthy, the healthy count throughout, and any failed request with its status code.
  9. Decide at steady state. If both routes answer, the floor holds in two zones and the error rate never moved, accept the release and close D5. If any gate opened, freeze and continue to the recovery step.
  10. Rehearse the rollback anyway. Even after a clean acceptance, revert the pin to the previous tag, apply, and probe both routes until they answer. This is the drill that turns D6 from a plan into evidence; record detection, decision and recovery timestamps.
  11. Return to the released version. Re-apply the new pin, confirm both routes and the healthy count, and leave the rehearsal account on the version the bundle describes.
  12. Reconcile. Plan the consumer root and the rehearsal root with the detailed exit code. Expect no changes from either; a diff means the rehearsal changed something the release does not own.
  13. Clean and hand over. Destroy the fixture, then the rehearsal root, then confirm the tag-based inventory is empty. Attach the evidence to the tag and remove the credentials from the workspace.

Expected observation. A green plan suite proves the interface and the wiring; the apply proves the provider accepts the arguments; the probe proves the service answers. The refresh moves the fleet while the healthy count never drops below the floor, and the rehearsed rollback is a single pin change followed by one apply. Every claim in the bundle points at one of those three instruments rather than at the apply exit code.

Failure checks. The review fails if a negative run passes on an invalid value, if the readiness probe passes while the target group health check uses the liveness path, if the plan replaces the listener during a release change, if the measurement has no baseline, if the rollback pin no longer exists, or if cleanup leaves an object that no tag can find.

Cost boundary. One load balancer, four small instances for a few hours, a handful of probe requests and the certificate if you rehearse TLS. Set a ceiling of USD 5 for a four-hour window in D1, keep the fleet at the desired count, and treat any spend beyond the ceiling as a stop rule rather than a surprise. Confirm current pricing before the apply.

Cleanup. Destroy the readiness fixture, destroy the rehearsal root, confirm targets and instances are gone, delete the certificate if one was issued for the lab, remove saved plans and probe logs that carry account details, and finish with an inventory query by the run tag. Keep the evidence and discard the credentials.

Evidence to keep. The contract record, the ownership map, the annotated tag, the changelog, the plan digest, the contract-suite results with the removed-rule check, the apply and probe output, the baseline and after tables with timestamps, the recovery log and the empty inventory result.

References (verified 6 November 2026): Module sources and version pins, terraform test, aws_lb_target_group, aws_autoscaling_group instance refresh, aws_lb_listener, Autoscaling instance refresh, ELB connection draining.

A versioned module is a promise with a test suite attached. The project passes when a consumer can pin the tag, read the changelog, run the examples and get the same plan; when a reviewer can name which test proves which claim; and when a replacement can be measured, stopped and reversed without guessing. That is a stronger result than a green apply, and it is what makes the module reusable by someone who has never met you.