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-lab5with this file:servers.csvhostname,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
Tick a task when it is done. Only your browser remembers it.
- Read
servers.csvwithcsv.DictReader(not withsplit(",")— the owner"ops, dev"has a comma). - Check every row:
ram_gbmust be a whole number andipa valid IPv4 address. Print a warning with the line number for a bad row and skip it. - Group the good rows by
roleand count the RAM per role. - Write
inventory.json(pretty, sorted keys) with the groups and asummarypart (number of servers, RAM per role). - Write
inventory.yamlin the Ansible inventory shape:all: children: <role>: hosts: <hostname>: ansible_host: <ip>. - Read the input and output file names from
report.tomlwithtomllib(part of Python 3.11+). - The script exits with code
1if 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), andexit=1. inventory.jsonhas 4 servers insummary, andram_by_roleis{"cache": 4, "db": 32, "web": 16}.- The YAML part
dbhas onlydb01withansible_host: 10.0.2.21.
Hints
Show the hints
ipaddress.IPv4Address(text)raisesValueErrorfor 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
- The config file.report.toml
[files] input = "servers.csv" json = "inventory.json" yaml = "inventory.yaml" - 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) - Run it.
My notes
No notes yet.