Skip to main content
AUTOMATING IT OPERATIONS / LESSON 04

Infrastructure Monitoring.

Turn one-time investigations into reliable monitoring. Use explicit health contracts, consecutive failure thresholds, configuration baselines, logging, and safe schedules to detect issues without creating alert storms.

Intermediate → Advanced120–170 minutes plus an optional offline monitoring mini-project8 original coding challengesOffline monitoring mini-projectNo live device access
00

What you'll learn

The first three phases taught you to write safe operations scripts, gather bounded network evidence, and plan integrations with ticketing and notification services. Now you'll process observations over time, build an alert lifecycle, and make monitoring decisions that don't invent healthy states or duplicate incidents.

  • Distinguish a scheduled monitoring check from a one-time troubleshooting script, and define the exact service signal each check measures.
  • Validate a device inventory, health-check policy, timeouts and intervals before collecting observations.
  • Represent probe results as timestamped evidence that preserves healthy, failed and unknown states rather than guessing.
  • Evaluate consecutive failures, recovery thresholds, stale observations and maintenance windows without creating alert storms.
  • Compare observed configurations with explicit, versioned baselines and treat changes as review-worthy rather than automatically malicious.
  • Build structured, privacy-aware logging and summary reports with UTC timestamps and independent per-target outcomes.
  • Explain interval scheduling, monotonic timing, overlapping runs, bounded retries, backoff and safe shutdown.
  • Create an independent offline monitor that reads simulated observations, detects state transitions and prepares deduplicated alerts.
Practice boundary: JoeLearns executes actual Python in its isolated browser workbench using fictional monitoring cycles. It does not access networks, run background jobs, send notifications, rewrite DNS, or open live service connections. The optional local project is also fully offline.

Prerequisite: Complete IT Service Integrations or understand dictionaries, validation, response handling and incident keys. The shared course navigator above tracks the ordered Learn → Practice milestones; On This Page is just the current lesson's reading outline.

A SINGLE CHECK IS NOT MONITORING
01

Define monitoring signals and a service contract

Phase 02 taught you to collect truthful network observations. Phase 03 taught you to prepare service-desk actions. Monitoring connects those ideas across time. A monitoring system must define what was checked, how often, what qualifies as success, and what should happen when the evidence is missing. A successful TCP handshake tells you a port accepted a connection; it does not establish that an application is working correctly. Use a service-specific health contract rather than an unqualified online/offline label.

Choose meaningful checks

For a website, an expected HTTP response may matter more than ping. For a backup job, last successful completion time may be more relevant than a responding service port.

Define the check policy

Document an approved target, a method, expected result, deadline and reasonable check interval. Record when the check applies, including planned maintenance.

Separate reachability and health

A host can resolve, accept TCP, and still return application errors. Record the measured layer in the result so a technician understands what the signal proves.

PYTHON / REASON THROUGH THE RESULTRead-only fictional example
sample = {'host':'APP-01','check':'https','tcp_connected':True,'http_status':503}

def classify_web(sample):
    if sample.get('tcp_connected') is not True:
        return 'not-verified'
    if sample.get('http_status') == 200:
        return 'healthy-http'
    return 'http-unhealthy'

print(classify_web(sample))
A server accepts TCP 443 but returns HTTP 503. Is the service healthy? Reveal the explanation after predicting.

No. The TCP handshake succeeded but the application reported an unavailable response. Record a transport success and an application-level failure separately; the service's contract decides what is healthy.

Remember: Monitor named, measurable service behavior—not an ambiguous 'device online' claim.
GOOD MONITORING STARTS BEFORE THE LOOP
02

Validate inventory, monitoring policy and operational scope

A recurring job can make the same mistake hundreds of times. Validate its inputs before the first cycle: trustworthy device identity, explicit check type, supported interval, timeout, and approved ownership. Reject missing or duplicate targets. A numeric field should not accept Python True simply because booleans are subclasses of integers. Do not silently turn an invalid timeout into an unlimited wait.

Reject malformed targets

Normalize hostnames and service identifiers consistently. When two rows have conflicting definitions for the same check, require the inventory owner to resolve the ambiguity.

Set bounded timing

The interval limits how often the check runs; the timeout limits one attempt. A good policy avoids an impossible schedule in which a single check routinely outlasts its interval.

Know your authorization

An IP address in a subnet is not permission to monitor it indefinitely. Review the specific approved devices, endpoints, methods, rate, credentials and operational window.

PYTHON / REASON THROUGH THE RESULTRead-only fictional example
policy = {'check':'https','interval_s':60,'timeout_s':5}

def valid_policy(policy):
    return (policy.get('check') == 'https'
            and type(policy.get('interval_s')) is int
            and type(policy.get('timeout_s')) is int
            and policy['interval_s'] > policy['timeout_s'] > 0)

print(valid_policy(policy))
Why reject interval_s=True instead of treating it as a one-second interval? Reveal the explanation after predicting.

Python's bool inherits from int, so a loose isinstance(True,int) check accepts it. Requiring type(value) is int avoids configuration that only looks numeric. Also enforce sensible bounds and timeout smaller than the interval.

Remember: Validate a recurring job's policy once up front—and revalidate changed configuration before acting.
SAVE OBSERVATIONS, NOT ASSUMPTIONS
03

Model healthy, failed and unknown results accurately

An observation should identify the target, method, result, and observation time. Healthy means the defined success condition was confirmed. Failed means the probe returned evidence against that condition. Unknown means the measurement could not establish either result: a monitor may have crashed, timed out, lacked permission or missed its own deadline. Never count unknown as healthy or fabricate a latency measurement. Preserve raw error categories as non-secret diagnostics when useful.

A timeout has a scope

Timeout from one monitoring host does not prove the target is powered off. Record the check path and method, not a universal outage claim.

Use UTC event times

datetime.now(timezone.utc).isoformat() produces an aware timestamp for audit records. Distinguish when a probe was observed from when a report was generated.

Keep three distinct states

A healthy/failed boolean discards missing information. Use an explicit unknown state so alerting logic and trend reports do not hide monitoring blind spots.

PYTHON / REASON THROUGH THE RESULTRead-only fictional example
from datetime import datetime, timezone

event = {'host':'APP-01', 'check':'https', 'result':'unknown',
         'observed_at_utc':datetime.now(timezone.utc).isoformat()}
print(event['host'], event['result'])
If the monitor itself loses network access, should all 30 targets be marked failed? Reveal the explanation after predicting.

No. The monitor may be unable to measure any target. Record unknown observations and a separate monitor-health incident instead of reporting 30 confirmed service failures.

Remember: A failed health check and a failed measurement are not equivalent.
REDUCE NOISE WITHOUT HIDING REAL INCIDENTS
04

Use consecutive observations and recovery thresholds

One transient failure should not necessarily page a technician. Many monitors use a consecutive-failure threshold to enter an alert state and a recovery threshold to return to normal. This is hysteresis: different entry and exit conditions reduce flapping around a boundary. The policy must define what unknown observations do to an existing streak; in this lesson they reset consecutive-confirmed streaks and preserve any already-open alert for review. The purpose is consistent behavior, not ignoring incidents.

Alert on a sustained condition

For example, after three consecutive confirmed failures, open one incident for a target and check. Do not raise three separate tickets for the same continuing failure.

Recover on corroborating evidence

Two consecutive verified healthy observations may close a transient alert, if your operational policy permits automated closure. One healthy result may not be enough.

Treat unknown as incomplete evidence

A missing check must not be counted as healthy recovery or confirmed failure. Preserve the open state if already alerting, and flag stale or missing measurements separately.

PYTHON / REASON THROUGH THE RESULTRead-only fictional example
results = ['failed','failed','unknown','failed','failed','failed']
streak = 0
for state in results:
    streak = streak + 1 if state == 'failed' else 0
    print(state, streak, 'alert' if streak >= 3 else 'observe')
With a three-failure threshold, should failed → unknown → failed trigger an alert? Reveal the explanation after predicting.

Not under a consecutive-confirmed-failure policy. Unknown breaks the consecutive streak. A separate policy may alert on monitoring blindness, but it must not invent confirmed failures.

Remember: Make transition rules explicit: thresholds, recovery and unknown handling should never be accidental.
CHANGES NEED CONTEXT
05

Detect configuration drift against an approved baseline

A drift detector compares a current configuration snapshot with an approved, versioned expectation. Normalize only fields the comparison contract allows; do not 'fix' meaningful differences while parsing. For DNS configuration, an unexpected resolver might be a legitimate planned change, an outdated baseline, or a security concern. Report the divergence, source and baseline revision, then confirm its authorization before remediation. An unreachable device is not evidence that its configuration drifted.

Version the expectation

Record baseline owner, revision and last approval date. Otherwise a correct planned change can look malicious after a rollout.

Compare typed, normalized values

Normalize IP representations using ipaddress and compare complete allowed sets when policy permits. Avoid assuming DNS servers must be in a particular order unless that is operationally meaningful.

Separate detection and correction

Drift is an observation and an investigation trigger, not an instruction to overwrite production. Phase 05 will teach explicitly authorized, verified remediation.

PYTHON / REASON THROUGH THE RESULTRead-only fictional example
from ipaddress import ip_address
baseline = {'192.0.2.10','192.0.2.11'}
observed = [str(ip_address(x)) for x in ['192.0.2.11','192.0.2.10']]
print('matches' if set(observed) == baseline else 'review-drift')
An endpoint has one unrecognized DNS server but you cannot establish the approved baseline revision. Is it safe to rewrite the configuration? Reveal the explanation after predicting.

No. Record a review-required finding and verify the authoritative baseline and change approval first. A drift alert is not blanket permission to alter configuration.

Remember: Detect drift from a trusted baseline without promoting uncertainty to an automatic change.
EVIDENCE MUST SURVIVE THE NEXT RUN
06

Build trustworthy logs and operational summaries

Monitoring records are most useful when another person can understand them after the script exits. Structured JSON Lines lets you append independent event objects; Python's logging module offers levels and destinations. Record target, check, observation state, source, UTC timestamp, incident correlation key and a safe error category. Protect logs against accidental credential leakage and excessive volume. A service reporting success at 14:00 does not mean it was healthy at 14:15.

Log states and transitions

Keep individual observations separate from state changes such as alert opened, alert still open and recovery verified. Otherwise the same persistent failure may generate endless 'new' incident messages.

No secrets or fabricated timestamps

Never include authorization headers, API tokens or passwords. Use real aware timestamps at event creation rather than rewriting old observation times.

Make the handoff human-readable

Summarize observed failures, unknown checks, suppressed notifications and outstanding incidents. Distinguish accepted ticket updates from confirmed delivery or resolution.

PYTHON / REASON THROUGH THE RESULTRead-only fictional example
import json
record = {'host':'APP-01','check':'https','state':'unknown','source':'NOC-1'}
print(json.dumps(record, sort_keys=True))
# This prints a record; real logging needs retention and access controls.
A script submitted an alert to a ticketing API and got 202 Accepted. Can the monitoring log say the issue is resolved? Reveal the explanation after predicting.

No. The API accepted the request for processing. Log the submission and its status, then separately confirm processing and actual service recovery before reporting resolution.

Remember: Logs should record evidence and independently verified state transitions, never assumed success.
REPEATED WORK NEEDS BOUNDARIES
07

Schedule responsibly and avoid overlapping runs

A reliable monitor should run at a documented cadence without overlapping indefinitely. A simple loop with time.sleep(interval) delays after work completes, so actual start-to-start spacing includes execution time. A host scheduler, timer or managed job runner can be more appropriate for production; choose the tool that offers predictable restarts, logs, and ownership. Inside a running process, time.monotonic() is useful for measuring elapsed time because wall clocks can jump. Always bound iteration count and concurrency in exercises.

Monotonic for elapsed durations

Use datetime with timezone.utc for audit times; use time.monotonic() for deadlines and elapsed intervals within a running process. They solve different problems.

Prevent overlap and overload

Choose explicit timeouts and worker limits, skip or queue overlapping cycles according to policy, and do not hammer a struggling service with unbounded checks.

Shutdown must be deliberate

Catch expected exceptions, support cancellation or a stop signal, and flush evidence safely. Do not create a hidden forever-loop just to make the demo feel realistic.

PYTHON / REASON THROUGH THE RESULTRead-only fictional example
durations = [3, 8, 2]  # fictional probe durations in seconds
interval = 10
for elapsed in durations:
    print('scheduled-after', max(0, interval - elapsed), 'seconds')
# A real scheduler must also handle overlap, deadlines and jitter.
With a 60-second sleep after every 20-second probe, how often does each probe start? Reveal the explanation after predicting.

Approximately every 80 seconds, not every 60 seconds. Account for execution duration or use a scheduler with explicitly defined start times, deadlines and overlap rules.

Remember: A repeatable cadence needs timeouts, overlap policy and an intentional stop mechanism.
ONE CONTINUING PROBLEM IS ONE INCIDENT
08

Manage alert transitions, deduplication and maintenance windows

Monitoring produces many observations, but operations teams should receive meaningful state changes. Use a stable key identifying the target and check, track whether an incident is already open, and create a notification only when an alert opens or genuinely recovers. A maintenance window may suppress pages while still collecting evidence; suppressed is not healthy. A silenced monitor that stops reporting entirely is a different risk. Never auto-close a ticket until the appropriate verification and workflow rules are satisfied.

Deduplicate at the event boundary

The same incident key should survive multiple failed cycles. Record ongoing failure observations without posting a new ticket each minute.

Maintenance suppresses messages, not facts

Log status during approved maintenance. Label the alert suppressed with the reason and schedule so missing pages cannot be mistaken for healthy service.

Recover with verified evidence

A recovery notice can be drafted only after the service check meets the defined recovery threshold. Confirm any ticket state change through the service API.

PYTHON / REASON THROUGH THE RESULTRead-only fictional example
open_incidents = {'hq:app-01:https'}
key = 'hq:app-01:https'
if key in open_incidents:
    print('record-observation')
else:
    print('consider-new-alert')
# No ticket API calls are performed.
During approved maintenance, every check reports HTTP 503. Should the summary mark the website healthy because paging is disabled? Reveal the explanation after predicting.

No. Record the unsuccessful check and the active suppression context. Alert delivery is intentionally muted; the health observation has not changed.

Remember: Deduplication and maintenance controls alter notification decisions, not the underlying evidence.
09 / OPTIONAL LOCAL PROJECT
09

Build an offline infrastructure health monitor

Create a small Northstar Ops monitoring simulator with a fictional device inventory and successive JSON observations. It uses no network sockets or real credentials. Unlike a single script run, it should preserve state between several simulated cycles and produce an auditable set of transitions.

PYTHON / A FINITE OFFLINE MONITORING CYCLENo sockets or scheduling
cycles = [
    {'APP-01': 'healthy'},
    {'APP-01': 'failed'},
    {'APP-01': 'failed'},
]
for number, cycle in enumerate(cycles, 1):
    print(number, cycle['APP-01'])
# Next: add threshold state, UTC logs and report-only alert decisions.
  1. Create monitor-lab/ with inventory.csv, policy.json, cycles.json, monitor.py and README.md on a local Git feature branch.
  2. Populate a tiny fictional device fleet: APP-01 HTTPS, DB-01 backup freshness and SW-01 management service. Validate every source file and reject duplicate monitor keys before processing cycles.
  3. Define a monitoring policy with check interval, timeout, three confirmed failures to open an alert and two consecutive healthy observations to recover. Explicitly document how unknown samples affect streaks.
  4. Process a finite list of simulated cycles rather than writing an endless loop. Include normal, degraded, unknown, maintenance-suppressed and recovered sequences.
  5. Compare one approved DNS baseline to a simulated observed set, log drift as review-required and do not rewrite the source configuration.
  6. Produce JSON Lines events with real UTC timestamps and per-check results; separately create a summary showing open alerts, recovered alerts, unknown probes and suppressed notification decisions.
  7. Run changed-input tests: missing host, duplicate device/check pair, malformed policy, failed → unknown → failed, an alert that persists across cycles, and a recovery requiring the full threshold. Commit source and README with no customer data.
Safety boundary: All device records and probe outcomes are fictional and processed offline. The browser coding clinic likewise executes only local Python against simulated samples; it never scans networks, sends tickets, restarts services or contacts monitored targets.
10 / WRITE THE CODE
10

Practice monitoring decisions with real Python

Eight independent challenges cover monitoring contracts, probe evidence, consecutive failures, alert state transitions, DNS baseline drift, scheduling gaps, maintenance-aware notifications and fleet handoffs. Each uses additional test cases to check behavior beyond the sample.

After reading, use the shared Continue Your Learning Path panel below to mark Lesson 04 complete and begin Practice. Complete its coding clinic before proceeding to safe remediation in the next phase.

11

Official references and further reading

The Python standard library provides the building blocks; production scheduling and notification policies still require an organization's operational requirements and approvals.

CONTINUE YOUR LEARNING PATH · AUTOMATING IT OPERATIONS

Complete the Practice milestone

You've reached the end of this written lesson. Your next step is practice: Infrastructure Monitoring · Python Coding Clinic. Complete that milestone before moving to the following lesson. You can revisit the explanation whenever you need it. Next: milestone 8 of 12.

Your completion marks are saved in this browser only.