4.18 Real-World DevOps Examples
Correct Python syntax applied in realistic DevOps scripts — a configuration module, a log-cleanup automation script, a log-processing scanner, and a boto3 AWS script.
Seeing correct syntax structure in realistic scripts reinforces the rules covered across this chapter better than isolated snippets — here’s how the pieces come together in practice.
Configuration Scripts
A typical config module: constants at the top, dictionary literal for structured settings — direct application of 4.9 Constants and 4.10 Literals.
# config.py
MAX_RETRIES = 3
TIMEOUT_SECONDS = 30
DATABASE = {
"host": "localhost",
"port": 5432,
"name": "prod_db",
}
Automation Scripts
A file-cleanup script showing imports, a function block, and the entry-point guard together — the full layout from 4.2 Structure of a Python Program in action.
import os
def remove_old_logs(folder, days=7):
for filename in os.listdir(folder):
print(f"Checking {filename}")
if __name__ == "__main__":
remove_old_logs("/var/log/app")
Log Processing Script Structure
A minimal but complete log-scanning script — notice the consistent indentation nesting a for loop inside a with block.
def count_errors(log_path):
error_count = 0
with open(log_path) as f:
for line in f:
if "ERROR" in line:
error_count += 1
return error_count
AWS Script Layout
A boto3-based script following the same import → constants → function → entry-point pattern used throughout this chapter.
import boto3
REGION = "us-east-1"
def list_running_instances():
ec2 = boto3.client("ec2", region_name=REGION)
return ec2.describe_instances()
if __name__ == "__main__":
list_running_instances()
Quick Interview Answer
“Real DevOps scripts follow the same layout as any other Python file: imports, then constants (a config dict, an AWS region, retry counts), then function definitions, then an
if __name__ == '__main__':guard. Whether it’s cleaning up log files withos, scanning a log for errors withwith open(...), or listing EC2 instances withboto3, the underlying syntax rules — indentation, colons, blocks — never change.”
Common Mistakes
- Hardcoding values like AWS region or file paths directly inside functions instead of pulling them from module-level constants, making the script harder to reconfigure.
- Forgetting the
withstatement when opening a file, leaving it to rely on garbage collection to eventually close the file handle.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form