Advanced
Searching inLabs
How to search
  • Search a task or a tool (lvm, selinux, @podman); filter by level and by book or course.
  • With an empty search box, a filter alone lists the labs — for example all hard labs of one course.
  • "two words" finds the exact phrase.
  • Plain words find names, texts and examples.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search
Try:

Lab 5.1Python, Chapter 5

Turn a CSV export into JSON and YAML reports

Level
Easy
35 min
Machines
any computer with Python 3.10 or newer (PyYAML for task 5)
Status
Not started

Goal

A typical admin job: the asset system gives you a CSV export, your monitoring wants JSON, and your Ansible inventory wants YAML. Write one script that reads the CSV safely, checks every row, groups the servers, and writes both formats. Settings come from a small config file, not from the code.

Before you start

  • python3 --version (3.10+). For YAML: pip install pyyaml (in a virtual environment if you like).
  • Make the folder ~/py-lab5 with this file:
    servers.csv
    hostname,ip,role,ram_gb,owner
    web01,10.0.1.11,web,8,ops
    web02,10.0.1.12,web,8,ops
    db01,10.0.2.21,db,32,dba
    db02,10.0.2.22,db,thirty-two,dba
    cache01,10.0.3.31,cache,4,"ops, dev"

Tasks

  1. Read servers.csv with csv.DictReader (not with split(",") — the owner "ops, dev" has a comma).
  2. Check every row: ram_gb must be a whole number and ip a valid IPv4 address. Print a warning with the line number for a bad row and skip it.
  3. Group the good rows by role and count the RAM per role.
  4. Write inventory.json (pretty, sorted keys) with the groups and a summary part (number of servers, RAM per role).
  5. Write inventory.yaml in the Ansible inventory shape: all: children: <role>: hosts: <hostname>: ansible_host: <ip>.
  6. Read the input and output file names from report.toml with tomllib (part of Python 3.11+).
  7. The script exits with code 1 if there was at least one bad row (so a cron job or CI can notice).

Check your work

python3 report.py; echo "exit=$?"
python3 -m json.tool inventory.json | head -15
python3 -c "import yaml; print(yaml.safe_load(open('inventory.yaml'))['all']['children']['db'])"
  • One warning for db02 (line 5), and exit=1.
  • inventory.json has 4 servers in summary, and ram_by_role is {"cache": 4, "db": 32, "web": 16}.
  • The YAML part db has only db01 with ansible_host: 10.0.2.21.

Hints

Show the hints
  • ipaddress.IPv4Address(text) raises ValueError for a bad address; int(text) too for a bad number.
  • enumerate(reader, start=2) gives the line number (line 1 is the header).
  • collections.defaultdict(list) makes grouping short.
  • json.dump(data, f, indent=2, sort_keys=True); yaml.safe_dump(data, f, sort_keys=False).
  • tomllib.load() needs the file opened in binary mode ("rb").

Solution

Show the solution
  1. The config file.
    report.toml
    [files]
    input = "servers.csv"
    json = "inventory.json"
    yaml = "inventory.yaml"
  2. The script.
    report.py
    #!/usr/bin/env python3
    """Read servers.csv, check it, write inventory.json and inventory.yaml."""
    import csv
    import ipaddress
    import json
    import sys
    import tomllib
    from collections import defaultdict
     
    import yaml
     
    with open("report.toml", "rb") as f:
        cfg = tomllib.load(f)["files"]
     
    groups, bad = defaultdict(list), 0
    with open(cfg["input"], newline="", encoding="utf-8") as f:
        for line, row in enumerate(csv.DictReader(f), start=2):
            try:
                row["ram_gb"] = int(row["ram_gb"])
                ipaddress.IPv4Address(row["ip"])
            except ValueError as err:
                print(f"warning: line {line} ({row['hostname']}): {err}", file=sys.stderr)
                bad += 1
                continue
            groups[row["role"]].append(row)
     
    ram = {role: sum(r["ram_gb"] for r in rows) for role, rows in groups.items()}
    report = {"groups": groups, "summary": {"servers": sum(len(v) for v in groups.values()), "ram_by_role": ram}}
    with open(cfg["json"], "w", encoding="utf-8") as f:
        json.dump(report, f, indent=2, sort_keys=True)
     
    inventory = {"all": {"children": {role: {"hosts": {r["hostname"]: {"ansible_host": r["ip"]} for r in rows}}
                                      for role, rows in groups.items()}}}
    with open(cfg["yaml"], "w", encoding="utf-8") as f:
        yaml.safe_dump(inventory, f, sort_keys=False)
     
    sys.exit(1 if bad else 0)
  3. Run it.
    python3 report.py; echo "exit=$?"
    warning: line 5 (db02): invalid literal for int() with base 10: 'thirty-two'
    exit=1
    cat inventory.yaml

My notes

No notes yet.

Lessons for this lab

Commands in this lab