Day 97: Custom Modules in Python
How to Build Custom Python Modules for Automating DevOps Tasks
Today, I learned how to create and use custom modules in Python β a major step toward building organized and reusable automation codebases for DevOps tasks.
π¦ What is a Module?
A module is simply a .py file containing functions, classes, or variables you want to reuse.
It allows code separation, organization, and reuse β just like how DevOps tools are broken into different services/components.
π Step 1: Create a Module
File: devops_utils.py
def deploy_app(app_name, server):
print(f"Deploying {app_name} to {server}...")
def restart_service(service):
print(f"Restarting {service}...")
env = "production"
βοΈ Step 2: Use the Module in Another Script
File: main.py
import devops_utils
print(f"Environment: {devops_utils.env}")
devops_utils.deploy_app("vprofile", "web01")
devops_utils.restart_service("nginx")
Output:
Environment: production
Deploying vprofile to web01...
Restarting nginx...
βοΈ Step 3: Use from ... import ...
You can also import only what you need:
from devops_utils import deploy_app
deploy_app("inventory-service", "web02")
π Why This Matters in DevOps
β
You can group all your server management functions in one module.
β
Create utility modules for logging, backups, deployments, and more.
β
Makes scripts clean, reusable, and collaborative across teams.
This is how real-world DevOps teams build their automation toolkits in Python.
π‘ Key Takeaways
Custom modules = reusable
.pyfilesOrganize code into logical units
Import modules across multiple scripts for automation




