Python Full Course for DevOps: A Beginner's Guide

·

5 min read

Python Full Course for DevOps: A Beginner's Guide

Table of contents

Variables are containers for storing data values. A data type defines what kind of data a variable can hold, such as integers, strings, or floats.

As a DevOps engineer, you’ll often store server details, configurations, or thresholds in variables. For example, storing server names, IP addresses, or monitoring thresholds.

Example:

# Variables for storing server details
server_name = "Production_Server"
ip_address = "192.168.1.1"
threshold = 85.5  # CPU usage threshold in percentage

print(f"Server: {server_name}, IP: {ip_address}, Threshold: {threshold}%")
  • Strings are sequences of characters (text data).

  • Conditional Statements allow decision-making in code using if, else, and elif.

You’ll use strings to handle text data such as file paths or server names. Conditional statements help you automate decisions, like determining whether a server is up or down.

Example:

# Check server status
server_status = "running"

if server_status == "running":
    print("The server is operational.")
elif server_status == "stopped":
    print("The server is down. Investigate immediately!")
else:
    print("Unknown server status.")
  • Lists are ordered, mutable collections of items.

  • Tuples are ordered, immutable collections of items.

Lists are useful for storing dynamic data, like a list of servers. Tuples are ideal for fixed data, such as environment names that won’t change.

# List of servers
servers = ["Server1", "Server2", "Server3"]

# Tuple for environment names
environments = ("Dev", "Staging", "Production")

# Add a new server to the list
servers.append("Server4")
print(servers)

# Attempting to modify a tuple will throw an error
# environments[0] = "QA"  # Uncommenting this will cause an error

Lecture 4: Dictionary & Set in Python

  • Dictionaries store data as key-value pairs.

  • Sets are unordered collections of unique items.

Use dictionaries to store configurations like server settings. Sets are great for ensuring unique values, like a list of unique server names.

Example:

# Dictionary for storing configurations
config = {
    "server_name": "Prod_Server",
    "IP": "192.168.1.10",
    "port": 8080
}

# Set for storing unique servers
servers = {"Server1", "Server2", "Server1"}  # Duplicates will be removed

print(config)
print(servers)
  • For Loop: Iterates over a sequence (list, tuple, etc.).

  • While Loop: Repeats as long as a condition is true.

Loops are perfect for automating repetitive tasks, such as checking the status of multiple servers or retrying failed connections.

Example:

# For loop to check server status
servers = ["Server1", "Server2", "Server3"]
for server in servers:
    print(f"Checking status of {server}...")

# While loop to retry a connection
attempts = 0
while attempts < 3:
    print(f"Retrying connection... Attempt {attempts + 1}")
    attempts += 1
  • Functions are reusable blocks of code.

  • Recursion occurs when a function calls itself.

Functions help modularize your code, making it reusable. Recursion can be useful in tasks like traversing directories or retrying failed operations.

Example:

# Function to check server health
def check_health(server):
    print(f"Checking health of {server}...")

# Recursion to count down retries
def retry_connection(attempts):
    if attempts == 0:
        print("No more retries left.")
        return
    print(f"Retrying... {attempts} attempts left.")
    retry_connection(attempts - 1)

check_health("Server1")
retry_connection(3)

File I/O allows you to read from and write to files.

File I/O is crucial for logging, reading configurations, or generating reports.

Example:

# Write server logs to a file
with open("server_logs.txt", "w") as file:
    file.write("Server1 is running.\n")
    file.write("Server2 is down.\n")

# Read the logs
with open("server_logs.txt", "r") as file:
    logs = file.read()
    print(logs)

OOP organizes code into classes (blueprints) and objects (instances).

You can model real-world entities like servers or deployments using classes and objects.

Example:

class Server:
    def __init__(self, name, ip):
        self.name = name
        self.ip = ip

    def start(self):
        print(f"Starting {self.name}...")

# Create an object
server1 = Server("Prod_Server", "192.168.1.10")
server1.start()
  • Inheritance allows a class to inherit attributes and methods from another class.

  • Polymorphism allows methods to have different implementations based on the object type.

  • Encapsulation hides the internal state of an object.

Inheritance helps model relationships between entities, like a base server class and specialized server types.

Example:

class Server:
    def __init__(self, name):
        self.name = name

    def start(self):
        print(f"Starting {self.name}...")

class WebServer(Server):
    def deploy_website(self):
        print(f"Deploying website on {self.name}...")

web_server = WebServer("Web_Server")
web_server.start()
web_server.deploy_website()

/