Object-Oriented Programming
(OOP) in Python
Object-Oriented Programming (OOP) is a way of organizing code using objects.
These objects have data (attributes) and actions (methods). Python uses OOP to
make coding simpler, reusable, and more structured.
Key OOP Concepts in Python
1. Class – A blueprint for creating objects.
2. Object – An instance of a class.
3. Encapsulation – Hiding internal details of an object.
4. Abstraction – Hiding implementation details and exposing only essential
features.
5. Inheritance – A class can inherit properties and methods from another class.
6. Polymorphism – Different classes can define methods with the same name,
enabling flexibility.
Basic Example
# Defining a class
class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand # Attribute
self.model = model
def drive(self): # Method
return f"{self.brand} {self.model} is driving."
# Creating an object (instance of the class)
my_car = Car("Toyota", "Camry")
# Accessing methods
print(my_car.drive()) # Output: Toyota Camry is driving.
Advanced OOP Features in Python
1. Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
# Creating an account object
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
2. Inheritance
class Vehicle:
def __init__(self, brand):
self.brand = brand
def drive(self):
return f"{self.brand} is moving."
class Car(Vehicle): # Inheriting from Vehicle
def honk(self):
return "Beep Beep!"
# Creating an instance
my_car = Car("Honda")
print(my_car.drive()) # Output: Honda is moving.
print(my_car.honk()) # Output: Beep Beep!
3. Polymorphism
python
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
# Polymorphism in action
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak())
# Output:
# Woof!
# Meow!
OOP in DevOps
Object-Oriented Programming (OOP) is useful in DevOps for structuring
automation, improving code reusability, and making infrastructure management
more efficient. Here are real-world use cases where OOP is applied in DevOps:
1. Infrastructure as Code (IaC)
● Example: Using Python classes to manage cloud resources like AWS S3,
EC2, and Lambda.
● Benefit: Encapsulation of cloud operations in reusable objects.
Example Code (AWS S3 Management with Boto3):
import boto3
class S3Bucket:
def __init__(self, bucket_name):
self.s3 = boto3.client("s3")
self.bucket_name = bucket_name
def create_bucket(self):
self.s3.create_bucket(Bucket=self.bucket_name)
return f"Bucket '{self.bucket_name}' created."
# Usage
bucket = S3Bucket("devops-bucket")
print(bucket.create_bucket())
2. CI/CD Pipelines
● Example: Organizing Jenkins pipeline stages as classes for modularity.
● Benefit: Reusable and maintainable pipeline automation.
Example Code (Jenkins API using OOP in Python):
import jenkins
class JenkinsPipeline:
def __init__(self, server_url, user, password):
self.server = jenkins.Jenkins(server_url, username=user, password=password)
def trigger_build(self, job_name):
self.server.build_job(job_name)
return f"Triggered build for {job_name}."
# Usage
jenkins_pipeline = JenkinsPipeline("http://localhost:8080", "admin", "password")
print(jenkins_pipeline.trigger_build("MyJob"))
3. Container Management with Docker SDK
● Example: Managing Docker containers using Python classes.
● Benefit: Object-oriented approach makes container operations reusable.
Example Code (Starting and Stopping Containers):
import docker
class DockerManager:
def __init__(self):
self.client = docker.from_env()
def start_container(self, container_name):
container = self.client.containers.get(container_name)
container.start()
return f"Started container: {container_name}"
# Usage
manager = DockerManager()
print(manager.start_container("nginx"))
4. Monitoring and Logging
● Example: Using OOP to structure monitoring alerts (e.g., Prometheus API).
● Benefit: Encapsulation of alerting logic into objects.
Example Code (Fetching Prometheus Metrics):
import requests
class PrometheusMonitor:
def __init__(self, prometheus_url):
self.url = prometheus_url
def get_metric(self, metric_name):
response = requests.get(f"{self.url}/api/v1/query", params={"query":
metric_name})
return response.json()
# Usage
monitor = PrometheusMonitor("http://localhost:9090")
print(monitor.get_metric("up"))
5. Configuration Management (Ansible, Terraform)
● Example: Wrapping Ansible playbook execution in Python classes.
● Benefit: Improves modularity and reduces redundant scripts.
Example Code (Ansible Playbook Execution with OOP):
import subprocess
class AnsibleManager:
def __init__(self, playbook_path):
self.playbook = playbook_path
def run_playbook(self):
result = subprocess.run(["ansible-playbook", self.playbook],
capture_output=True, text=True)
return result.stdout
# Usage
ansible = AnsibleManager("deploy.yml")
print(ansible.run_playbook())
Why Use OOP in DevOps?
✅ Modularity – Reusable components for cloud management, CI/CD, and
✅ Scalability – Easily extend functionality by adding new methods.
automation.
✅ Maintainability – Organized and structured code for DevOps automation.
✅ Encapsulation – Hides complex logic inside objects for simplicity.
Project: DevOps Automation with OOP
Goal:
✅ Automate AWS resource management
✅ Manage Docker containers efficiently
✅ Integrate with Jenkins for CI/CD
1️⃣ AWS Automation: Managing EC2 Instances
We'll create an EC2Manager class to start, stop, and terminate AWS EC2
instances using Boto3.
Python Code for EC2 Management
import boto3
class EC2Manager:
def __init__(self, region="us-east-1"):
self.ec2 = boto3.client("ec2", region_name=region)
def create_instance(self, ami_id="ami-0c55b159cbfafe1f0",
instance_type="t2.micro"):
response = self.ec2.run_instances(
ImageId=ami_id,
InstanceType=instance_type,
MinCount=1,
MaxCount=1
instance_id = response["Instances"][0]["InstanceId"]
return f"EC2 Instance {instance_id} created."
def stop_instance(self, instance_id):
self.ec2.stop_instances(InstanceIds=[instance_id])
return f"EC2 Instance {instance_id} stopped."
def terminate_instance(self, instance_id):
self.ec2.terminate_instances(InstanceIds=[instance_id])
return f"EC2 Instance {instance_id} terminated."
# Usage Example
ec2_manager = EC2Manager()
print(ec2_manager.create_instance()) # Creates an EC2 instance
🔹 OOP Benefits: Encapsulation, Reusability, and Scalability.
2️⃣ Docker Automation: Managing Containers
We'll create a DockerManager class to start, stop, and list Docker containers.
Python Code for Docker Management
import docker
class DockerManager:
def __init__(self):
self.client = docker.from_env()
def list_containers(self):
return [container.name for container in self.client.containers.list(all=True)]
def start_container(self, container_name):
container = self.client.containers.get(container_name)
container.start()
return f"Container {container_name} started."
def stop_container(self, container_name):
container = self.client.containers.get(container_name)
container.stop()
return f"Container {container_name} stopped."
# Usage Example
docker_manager = DockerManager()
print(docker_manager.list_containers()) # List all containers
🔹 OOP Benefits: Reusability and Better Code Organization.
3️⃣ CI/CD Pipeline: Triggering Jenkins Builds
We'll create a JenkinsPipeline class to trigger Jenkins builds.
Python Code for Jenkins Integration
import jenkins
class JenkinsPipeline:
def __init__(self, server_url, user, password):
self.server = jenkins.Jenkins(server_url, username=user, password=password)
def trigger_build(self, job_name):
self.server.build_job(job_name)
return f"Triggered build for {job_name}."
# Usage Example
jenkins_pipeline = JenkinsPipeline("http://localhost:8080", "admin", "password")
print(jenkins_pipeline.trigger_build("MyJob"))
🔹 OOP Benefits: Scalability and Code Reusability.
4️⃣ Bringing Everything Together
Combine all three classes in a single Python script to fully automate AWS,
Docker, and Jenkins in a DevOps workflow.
Python Code for Full DevOps Automation
class DevOpsAutomation:
def __init__(self):
self.ec2_manager = EC2Manager()
self.docker_manager = DockerManager()
self.jenkins_pipeline = JenkinsPipeline("http://localhost:8080", "admin",
"password")
def deploy_infrastructure(self):
ec2_instance = self.ec2_manager.create_instance()
print(ec2_instance)
def manage_containers(self):
print("Available containers:", self.docker_manager.list_containers())
print(self.docker_manager.start_container("nginx"))
def trigger_ci_cd(self):
print(self.jenkins_pipeline.trigger_build("MyJob"))
# Usage Example
automation = DevOpsAutomation()
automation.deploy_infrastructure() # Create EC2 instance
automation.manage_containers() # Manage Docker
automation.trigger_ci_cd() # Start Jenkins build
🔹 OOP Benefits:
✅ Encapsulation: Each service (AWS, Docker, Jenkins) is in its own class.
✅ Modularity: We can easily replace or extend functionalities.
✅ Reusability: The same code can be used across multiple projects.
Real-World Use Cases
1️⃣ Infrastructure Automation – Provision AWS instances dynamically.
2️⃣ Container Orchestration – Start and stop containers based on CI/CD
workflows.
3️⃣ CI/CD Pipeline Integration – Trigger automated Jenkins builds.