01 / INVENTORY AND CONFIGURATION · LESSON 01

Build a useful server inventory

Validate a CSV export and turn active servers into a consistent, numeric inventory.

15 min · learn at your pace

Begin with an export you can explain

A useful administration script starts by deciding which records it can trust. csv.DictReader turns each CSV record into a dictionary, but every field still arrives as text. Convert values deliberately instead of relying on whether a string is truthy: the string "false" is not an empty value.

This exercise accepts explicit true/false active flags and positive whole-byte memory values. Normalize host and environment labels with strip().casefold(). The normalization rule belongs to this fictional inventory; it is not a claim that every naming system has identical rules.

Keep errors beside useful data

Return accepted active servers and a separate error list. A record number starts at two because the header is record one. CSV fields can contain quoted newlines, so this is a logical record number rather than a physical file line. Keep the first valid occurrence of each normalized hostname, even if it describes an inactive server. A later duplicate is ambiguous and needs review.

Convert bytes to GiB using 1024 ** 3 and retain a numeric result. Sorting numbers after formatting them into text can give surprising results. Sort the final inventory by host so two runs can be compared easily.

All input is supplied in the browser filesystem. This function does not query hardware or connect to a server. The main-guard example prints its result; Check calls the function with other exports as well.

Try an example.py
import csv
from pathlib import Path
with Path("inventory.csv").open(encoding="utf-8", newline="") as handle:
    for row in csv.DictReader(handle):
        print(row["host"], row["memory_bytes"])
YOUR TURN

Put it into practice.

Define read_inventory(path), returning (servers, errors). Require CSV headers host,active,memory_bytes,environment; missing headers raise ValueError and missing files raise FileNotFoundError. Validate nonempty host/environment, true/false active flags, and positive ASCII whole-byte memory. Normalize host/environment with strip().casefold(). Keep the first valid host record, including inactive ones; reject later duplicates. Return active servers as host,environment,memory_gib (numeric bytes / 1024**3), sorted by host. Errors use logical record numbers starting at 2 and reasons invalid record or duplicate host, in input order.

See an explained solution
One way to solve it.py
import csv
from pathlib import Path

def read_inventory(path):
    servers, errors, seen = [], [], set()
    with Path(path).open(encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        required = {"host", "active", "memory_bytes", "environment"}
        if not required.issubset(reader.fieldnames or []):
            raise ValueError("Inventory header is incomplete")
        for number, row in enumerate(reader, 2):
            try:
                host = row["host"].strip().casefold()
                active = row["active"].strip().lower()
                environment = row["environment"].strip().casefold()
                raw_memory = row["memory_bytes"].strip()
                if not host or not environment or active not in ("true", "false") or not raw_memory.isascii() or not raw_memory.isdecimal():
                    raise ValueError("Invalid inventory record")
                memory = int(raw_memory)
                if memory <= 0:
                    raise ValueError("Memory must be positive")
            except (ValueError, AttributeError):
                errors.append({"record": number, "reason": "invalid record"})
                continue
            if host in seen:
                errors.append({"record": number, "reason": "duplicate host"})
                continue
            seen.add(host)
            if active == "true":
                servers.append({"host": host, "environment": environment, "memory_gib": memory / (1024 ** 3)})
    return sorted(servers, key=lambda row: row["host"]), errors

if __name__ == "__main__":
    print(read_inventory("inventory.csv"))

The reader distinguishes invalid data from inactive systems, retains duplicate evidence in errors, and converts byte counts before any display formatting.