Modules, files & Python for DevOps
Real scripts read files, talk to APIs and use other people's code. This chapter covers how Python pulls in libraries, how it handles files and JSON, and the kinds of automation DevOps engineers actually write with it.
Modules and packages
A module is just a .py file; import loads it so you can use what's inside. Python ships with a big standard library (os, json, datetime, subprocess, pathlib…), and thousands more third-party packages live on PyPI, installed with pip.
import name. Only PyPI packages need installing first, ideally into the project's virtual environment.import os # use as os.getenv(...)
from datetime import datetime # import one name directly
import subprocess as sp # import under a shorter alias
$ pip install requests boto3 # third-party packages from PyPI
Different projects need different package versions, so each project should get its own virtual environment: python3 -m venv .venv, then source .venv/bin/activate. pip freeze > requirements.txt records the exact versions, and pip install -r requirements.txt recreates them on another machine.
When a file is run directly, the special variable __name__ is "__main__"; when it's imported it's the module's name. So code under if __name__ == "__main__": runs only when you execute the file, not when another script imports its functions.
Reading and writing files
with open("hosts.txt") as f: # "r" (read) is the default
for line in f:
print(line.strip())
with open("report.txt", "w") as f: # "w" overwrites the file
f.write("all good\n")
with open("app.log", "a") as f: # "a" appends to the end
f.write("deploy finished\n")
with closes the file automatically when the block ends, even if an error happens in the middle.
JSON: the format APIs speak
JSON maps straight onto Python: objects become dicts, arrays become lists. json.load(f) / json.dump(data, f) work with files; json.loads(text) / json.dumps(data) work with strings.
What Python is used for in DevOps
- Scripting and automation: replacing long, fragile shell scripts: rotating logs, cleaning up old backups, renaming thousands of files.
- Talking to APIs: the
requestslibrary calls any REST API. The Nana course ends with a script that lists projects from the GitLab API. - Cloud automation: AWS's
boto3library creates and manages resources from code. The Cloud Champ video launches an EC2 server and rotates a database password with it. - Glue for tools: Ansible is written in Python, and CI pipelines often call small Python scripts for checks and reports.
- Monitoring: small web apps (for example with Flask) that report CPU, memory or disk use, or send alerts.
import requests
resp = requests.get("https://api.github.com/repos/python/cpython", timeout=10)
resp.raise_for_status() # error on 4xx/5xx
data = resp.json() # JSON body -> dict
print(data["stargazers_count"])
import boto3
ec2 = boto3.client("ec2", region_name="eu-central-1")
for r in ec2.describe_instances()["Reservations"]:
for i in r["Instances"]:
print(i["InstanceId"], i["State"]["Name"])