What you'll learn
Phase 04 taught you to detect sustained failures and configuration drift without manufacturing evidence or flooding the service desk. Phase 05 addresses the next operational responsibility: deciding whether an action is justified, designing a bounded and reversible change, and proving the problem was actually resolved. The shared course navigator above owns your Learn → Practice progression; this lesson's On This Page outline is for reading sections only.
- Explain why detection, diagnosis, approval, execution, and resolution are separate stages of an operational change.
- Require exact target identity, environment, approved action and expected revision in preflight checks.
- Produce deterministic dry-run plans and reject incomplete or stale authorization rather than attempting a write.
- Capture a safe before-state snapshot and specify failure/rollback conditions before proposing any change.
- Choose no-change for already compliant targets and handle concurrency and retry ambiguity safely.
- Design independent post-change verification covering configuration, service state and actual application behavior.
- Respond to partial failure or unknown outcomes with stop conditions, reconciliation and escalation.
- Build an audit-ready remediation handoff without leaking secrets or prematurely resolving tickets.
Prerequisite: Complete Infrastructure Monitoring or understand monitoring evidence, incident keys, validation and operational approvals. If you're unsure about conditional logic or defensive error handling, revisit Applied Python · Reliability.
Separate detection, diagnosis and change authorization
A monitoring alert is evidence that a defined check failed; it is not an authorization to modify production. Before remediation, determine the affected service, confirm the fault through independent evidence, establish who owns the target, and check the organization's incident or change-management process. Keep your Python script capable of producing a reviewable plan without executing it. Even read-only evidence must be scoped to systems you are permitted to inspect.
Observation → hypothesis
Write down precisely what the monitor observed and what it did not measure. A timed-out HTTPS request might be a network path issue, a blocked probe, or an unhealthy application; select additional checks that distinguish those possibilities.
Hypothesis → intended change
Choose the smallest authorized correction that is supported by evidence. Record the target, requested change, expected current state, desired state and required approval before doing any write operation.
No change is sometimes the safe outcome
If evidence conflicts, an approver is unavailable, scope is unclear, or the target identity cannot be verified, return review-required. A script that refuses an unsafe change is behaving correctly.
finding = {'host':'APP-01','check':'https','state':'unknown'}
# A review recommendation is not a change command.
def recommend(finding):
if finding['state'] == 'unknown':
return 'collect-more-evidence'
return 'review-with-owner'
print(recommend(finding))A single monitoring node times out connecting to APP-01. Is that enough reason to restart the application service automatically? Reveal the explanation after predicting.
No. The timeout may be caused by the monitoring path, firewall, DNS or other conditions. Confirm the diagnosis and approved scope first; avoid a disruptive change based on an ambiguous probe.
Design a preflight check that fails closed
A change plan is stale as soon as the environment changes. Immediately before an approved action, re-check the device's identity, environment, current configuration and policy baseline. Compare the observed revision with the change request's expected revision so a different technician's work cannot be overwritten accidentally. Missing data, conflicting inventory, incorrect scope and unapproved execution should all stop the operation before side effects occur.
Exact target and environment
Treat production and test targets as different entities. A host label alone is not enough when the same name may exist in several sites or tenants. Match the stable resource ID and environment recorded in the approval.
Expected-state guards
Require a documented before-state such as config revision r7 or service mode stopped. If the observed revision is r8, an update prepared for r7 must be revisited instead of blindly applied.
Bounded permissions and execution
Use explicit operation allowlists, time windows, operator identity, backups and change approval where appropriate. Dry-run remains the default; an opt-in apply mode should never silently bypass missing prerequisites.
request = {'target':'APP-01','expected_rev':'r7'}
observed = {'target':'APP-01','revision':'r8'}
if observed['target'] != request['target']:
print('stop: wrong target')
elif observed['revision'] != request['expected_rev']:
print('stop: stale plan')
else:
print('preflight match; approval still required')The approved change expects revision r7, but the target now reports r8. Should the tool apply the original patch? Reveal the explanation after predicting.
No. The current state changed after planning. Reconcile the difference and obtain an updated plan or approval. Do not overwrite changes you cannot account for.
Create deterministic dry-run plans with limited scope
An automation should explain every proposed effect before changing anything. Construct a structured plan identifying one approved target, action, expected state, intended state and dry-run status. Make the plan deterministic so reviewers can compare it between runs. The apply step must independently re-validate state and authorization; changing a dry_run field in a dict does not itself prove permission. Prefer a human-readable plan backed by machine-checkable fields.
Stable plan identity
Use meaningful identifiers and normalized values rather than generating a different plan on each execution. Keep the plan contents reviewable without exposing tokens or credentials.
Minimal blast radius
Limit a first change to one target or a small explicitly approved batch. A safe tool does not transform a single-host request into a fleet-wide restart.
No writes during preview
Dry runs may validate inputs and calculate differences, but should not write configurations, call live update APIs, update tickets or send messages. Treat all side effects as opt-in.
def build_plan(host, before, after):
return {
'target': host,
'expected_state': before,
'desired_state': after,
'mode': 'dry-run',
}
print(build_plan('APP-01','disabled','enabled')['mode'])Can a successful dry-run be reused as permission to apply the same change next week? Reveal the explanation after predicting.
No. Approval scope, current state and maintenance windows may have changed. Revalidate those controls at execution time and require the explicit approved apply path.
Capture an authorized checkpoint and design rollback
Rollback is not simply reversing a command or restarting a service. Preserve the known-good configuration, current revision and relevant dependencies before modifying a target. Decide in advance which failures trigger rollback and how to determine whether rollback itself succeeded. For a simulated configuration change, copy the original state rather than keeping a reference to the same mutable dictionary. In production, follow supported backup and restore procedures appropriate to the system.
Snapshot before modifying
Save the exact scoped pre-change state and a reference to an approved backup or version. Avoid printing confidential configuration values in screenshots or logs.
Know when rollback applies
If post-change verification fails, avoid continuing downstream changes. Stop and consider the documented rollback procedure; some actions are irreversible or require human escalation.
Verify rollback independently
An attempted restore is not a successful restore. Read back the configuration, confirm revision and service behavior, and report partial recovery or unknown states if evidence is incomplete.
from copy import deepcopy
before = {'revision':'r7','feature':'off'}
checkpoint = deepcopy(before)
working = deepcopy(before)
working['feature'] = 'on'
# Fictional rollback; no external system is touched.
working = deepcopy(checkpoint)
print(working == before)A rollback command exits with code zero, but the service check is still failing. Can the incident be marked resolved? Reveal the explanation after predicting.
No. The command result alone does not prove the desired state was restored or the service recovered. Keep the issue unresolved and record the verification failure.
Make remediation idempotent and auditable
A controlled executor should act only when the current state matches its preflight expectation. If the desired state is already verified, an idempotent operation may safely report no-change rather than repeatedly toggling or restarting services. Where the remote API supports an optimistic concurrency token (such as an ETag or revision), use the documented conditional-update mechanism to avoid overwriting concurrent changes. Persist an operation ID and result without storing credentials.
Idempotency is action-specific
Setting a configuration value to a known state can be idempotent when implemented correctly; restarting a service on every retry usually isn't. Do not claim retries are safe without checking the operation's semantics.
Protect against concurrent changes
If a configuration revision differs from the planned before-state, abort and replan. Treat HTTP 409 or 412 conflicts according to the provider's documented API rather than forcing the update.
Capture execution outcomes separately
Record not-started, attempted, accepted, verified and failed states. A 202 Accepted response does not confirm that a remediation job finished successfully.
def proposed_action(current, desired):
if current == desired:
return 'no-change-needed'
return 'apply-only-after-revalidation'
print(proposed_action('enabled','enabled'))A configuration is already at the approved desired value. Should a script still restart the service just to 'make sure'? Reveal the explanation after predicting.
Not automatically. If verification confirms the desired state and no restart is required by the approved procedure, report no-change-needed. Unnecessary restarts introduce risk.
Verify recovery at multiple relevant layers
A successful API write, a zero exit code, or a service-start status does not by itself prove user impact has ended. Define pass criteria before applying: the desired configuration is present, the expected process or service is running, and the actual application health check succeeds from the appropriate location. For distributed systems, check the required replicas or client paths instead of one lucky probe. An unknown verification result must block automatic resolution.
Compare actual to desired state
Read back the relevant property or revision from the target. Record observed values and source; avoid treating the local plan as if it were live state.
Check service health, not merely transport
A listening port can coexist with an HTTP 503 or a failed transaction. Verify the application-specific success condition, such as expected response, completed job or successful name resolution.
Declare partial outcomes honestly
Classify each verification dimension as pass, fail or unknown. A script that cannot verify should produce a pending/manual-review outcome, not a fabricated resolution.
checks = {'configuration':'pass','process':'pass','application':'unknown'}
def verified(checks):
return all(value == 'pass' for value in checks.values())
print('resolved' if verified(checks) else 'not-yet-verified')The service manager reports 'running' but the application health endpoint returns HTTP 503. Can the resolution notification go out? Reveal the explanation after predicting.
No. The approved application-level verification still fails. Keep the incident open, capture the failed evidence and investigate or use the documented recovery plan.
Handle partial failure, unknown execution and escalation
A remediation workflow spans multiple operations. One may succeed while another times out or returns an ambiguous response. Fail closed on invalid preflight checks, stop dependent writes after a failed step, and reconcile uncertain outcomes before retrying potentially disruptive actions. Record the last known state, operation ID, target, safe error category and required operator follow-up. Do not erase an unresolved issue just because a fallback step ran.
Separate failed from unknown
A remote command that was rejected is different from a timed-out request that may have executed. In the latter case, re-read state before deciding whether to retry or roll back.
Use controlled stop conditions
Never execute step 2 if step 1 failed and step 2 requires its success. Decide whether rollback is safe or needs an operator, especially for multi-node changes.
Escalate unverified recovery
Keep the ticket open and provide a concise handoff: intended action, actual evidence, unresolved steps and safe next investigation. Do not claim a partial restore is complete.
steps = ['preflight-pass','apply-unknown','verify-pending']
if 'apply-unknown' in steps:
print('stop-dependent-writes; reconcile-current-state')
else:
print('continue-only-if-verified')A PATCH request times out during remediation. Is immediately replaying the PATCH always the safest move? Reveal the explanation after predicting.
No. The server may have performed the change but the response was lost. Check current state or use the documented idempotency/concurrency mechanism before retrying, and stop dependent operations meanwhile.
Record results and update incident status responsibly
Remediation ends with evidence and communication, not merely the last script line. Build an audit record showing what was approved, which target and revision were involved, the before-state checkpoint, attempted actions, observed verification outcomes and resulting ticket state. Keep audit data free of tokens and unnecessary sensitive configuration. Only transition an incident to resolved after agreed recovery checks succeed and the ticketing system confirms its update. Explain any remaining risk or follow-up work.
One clear source of truth
Use the service-desk ticket's confirmed identifier. Link safe operational evidence to it; don't invent a ticket ID or a recovery timestamp from a proposed change.
Communicate at the right confidence
Use completed only for verified work, attempted for a submitted command, and needs-review for ambiguous or partial results. Stakeholders should be able to distinguish restoration from ongoing investigation.
Preserve the learning record
Record the root-cause hypothesis separately from confirmed cause, note how rollback or preflight behaved, and capture preventative follow-up without automatically changing further systems.
report = {
'change':'CHG-205',
'target':'APP-01',
'before':'r7',
'after':'r8',
'configuration':'verified',
'application':'unknown',
}
print('resolved' if all(report[k] == 'verified'
for k in ('configuration','application')) else 'keep-open')The configuration is verified, but the application remains unreachable from the required check location. Should the ticket be marked resolved? Reveal the explanation after predicting.
No. Record the partial state, keep the incident open and escalate further investigation or rollback as appropriate. An approved configuration change is not proof the incident impact ended.
Simulate an approved web-service configuration repair
Work with fictional Northstar Ops service records—not WGU's DNS scenario. This project never talks to a server: it models a scoped feature-flag change on APP-01, including approved state, preflight, application, verification, failure and rollback decisions. Keep the entire workflow deterministic and rerunnable.
from copy import deepcopy
original = {'host': 'APP-01', 'revision': 'r7', 'mode': 'disabled'}
checkpoint = deepcopy(original)
proposal = deepcopy(original)
proposal['mode'] = 'enabled'
print('dry-run:', original['mode'], '->', proposal['mode'])
print('original unchanged:', original == checkpoint)- Create repair-lab/ with change_request.json, current_state.json, simulated_events.json, repair.py, and README.md on a local Git feature branch. Use only made-up APP-01 and APP-02 data.
- Write validate_request() to check exact target, environment, action, expected revision, desired value, change ID and approved status; reject unknown fields.
- Write preflight() that compares target identity, observed revision and maintenance-window authorization. Treat missing facts as blocked, never as implied approval.
- Build a dry-run report with ordered actions and expected outcomes; print the plan without modifying current_state.json. Capture a deep copy of a fictional before-state checkpoint.
- Write a separate simulation function that changes an in-memory copy of APP-01 only when all preflight conditions pass; rerunning with the desired value should produce no-change. Never call a live service manager, SSH or REST endpoint.
- Inject changed-revision, wrong-target, timeout/unknown, application-unhealthy and partial-rollback cases. Show why successful execution does not always imply recovery and why the next operation must stop when required evidence fails.
- Compare final state and application health to the documented verification contract. Produce a JSON report with attempted, accepted, verified, failed, unknown, rolled-back or pending outcomes, and keep the fictional ticket open when recovery remains unverified.
- Commit the simulator, test fixtures and README. Explain the blast-radius boundary, rollback criteria and lessons learned. Exclude real configuration exports, credentials and generated sensitive logs.
Practice safe recovery decisions with Python
Eight independent coding challenges cover change contracts, preflight and revision checks, safe dry runs, independent checkpoints, idempotency, recovery gates, partial-failure decisions and verified incident handoffs. Alternate test fixtures enforce the intended edge cases.
Use the shared Continue Your Learning Path panel below to mark Lesson 05 complete and begin the Practice milestone. Finishing the coding clinic will bring you up to date with the published content, while the independent capstone remains in development.
Official references and further reading
Local simulations use Python standard-library tools. Live remediation must follow the target service's official instructions, authorization requirements, transaction semantics and rollback procedures.
