Validate an administration policy
Turn configuration into a checked policy before reading or changing system data.
Validate the rules before applying them
A configuration file moves decisions out of a script, but it also moves mistakes there. A misspelled key, a negative age or the text "20" where a number is expected should stop the tool with a clear error. Silently substituting a permissive default can make a report look healthier than the evidence supports.
Validate the entire policy before touching any output. This exercise defines three required fields: a free-space threshold, a maximum backup age and the environments in scope. Additional fields may exist, but the validated result contains only those three. That gives the rest of the tool a small, predictable interface.
Be precise about Python's types
bool is a subclass of int. A simple isinstance(value, int) accepts True, even though a true/false flag is not a sensible backup age. Use an exact type check for this policy. Reject non-finite numbers as well: comparisons with NaN do not behave like ordinary threshold comparisons.
Normalize environment names using the same rule as the inventory reader, then remove duplicates and sort. Return a new dictionary rather than rewriting the caller's input. The resulting policy is convenient for deterministic tests, and the original configuration remains available when explaining a validation failure.
import json
policy = json.loads('{"min_free_percent":20,"backup_max_age_hours":24,"environments":["prod"]}')
print(type(policy["min_free_percent"]).__name__)
Put it into practice.
Define validate_policy(data). Require an object with min_free_percent: a finite int/float from 0 through 100 excluding bool; backup_max_age_hours: a positive int excluding bool; environments: a nonempty list of nonempty strings. Invalid policy raises ValueError. Return only these three keys, with environments stripped, casefolded, deduplicated and sorted. Ignore extra keys and do not mutate the input.
See an explained solution
import math
def validate_policy(data):
if not isinstance(data, dict):
raise ValueError("Policy must be an object")
minimum = data.get("min_free_percent")
age = data.get("backup_max_age_hours")
environments = data.get("environments")
if type(minimum) not in (int, float) or not math.isfinite(minimum) or not 0 <= minimum <= 100:
raise ValueError("min_free_percent must be between 0 and 100")
if type(age) is not int or age <= 0:
raise ValueError("backup_max_age_hours must be a positive integer")
if not isinstance(environments, list) or not environments or any(not isinstance(e, str) or not e.strip() for e in environments):
raise ValueError("environments must contain nonempty strings")
return {"min_free_percent": minimum, "backup_max_age_hours": age,
"environments": sorted({e.strip().casefold() for e in environments})}
if __name__ == "__main__":
print(validate_policy({"min_free_percent":20,"backup_max_age_hours":24,"environments":[" PROD ","prod"]}))
The validator makes policy failure a distinct, early error. It returns a canonical copy that downstream functions can trust without hiding invalid values behind defaults.