last-day

chevron-rightcore coneptshashtag

"""
=======================================================
 CORE PYTHON BASICS
=======================================================
"""

# ๐Ÿ”น Variables & Data Types
# What: It Store values (numbers, text, flags)
# Why: Needed for all scripts, from configs to counters
# How:
server_count = 5         # int
server_name = "web-01"   # str
is_active = True         # bool
cpu_usage = 75.5         # float
print(server_count, server_name, is_active, cpu_usage)
print(f"count = {server_count}, name = {server_name}, active = {is_active}, cpu = {cpu_usage}")

# ๐Ÿ”น Loops
# What: Repeat tasks
# Why: Iterate over servers, pods, files, etc.
# How:
servers = ["web-01", "web-02", "db-01"]
for s in servers:
    print("Checking server:", s)


# ๐Ÿ”น Conditionals
# What: Run logic based on conditions
# Why: Alerts, decisions in automation
# How:
cpu_usage = 85
if cpu_usage > 80:
    print("โš ๏ธ High CPU usage!")
elif cpu_usage > 50:
    print("Normal load")
else:
    print("Idle")


# ๐Ÿ”น Functions
# What: Reusable blocks of logic
# Why: Keep scripts modular and clean
# How:
def check_disk(disk_percent):
    if disk_percent > 90:
        return "Alert: Low disk space!"
    return "Disk usage OK."

print(check_disk(75))


# ๐Ÿ”น Comments & Docstrings
# What: Notes in code
# Why: Explain automation for teammates
# How:
def restart_service(service):
    """
    Restart a given service on a Linux system.
    service: str โ†’ service name (nginx, mysql, etc.)
    """
    print(f"Restarting {service}...")
    # (real code would use subprocess here)

restart_service("nginx")


"""
=======================================================
 DATA STRUCTURES
=======================================================
"""

# ๐Ÿ”น Lists
# What: Ordered collection
# Why: Store IPs, servers, logs
# How:
ips = ["10.0.0.1", "10.0.0.2"]
ips.append("10.0.0.3")
print("All IPs:", ips)


# ๐Ÿ”น Tuples
# What: Immutable collection
# Why: Useful for constants like version numbers
# How:
version = (1, 24, 3)  # k8s version
print("Cluster version:", ".".join(map(str, version)))


# ๐Ÿ”น Dictionaries
# What: Key-value mapping
# Why: Store configs, JSON responses
# How:
server = {"name": "web-01", "ip": "10.0.0.1", "status": "active"}
print("Server name:", server.get("name"))
for k, v in server.items():
    print(k, "=>", v)


# ๐Ÿ”น Sets
# What: Unique collection
# Why: Deduplicate IPs or hosts
# How:
hosts = {"web-01", "db-01", "web-01"}
print("Unique hosts:", hosts)


"""
=======================================================
 FILE & SYSTEM HANDLING
=======================================================
"""

import os
import subprocess
from pathlib import Path

# ๐Ÿ”น File I/O
with open("servers.txt", "w") as f:
    f.write("web-01\nweb-02\n")

with open("servers.txt", "r") as f:
    print("Servers from file:", f.readlines())


# ๐Ÿ”น OS Module
print("Home dir:", os.environ.get("HOME"))
print("Join path:", os.path.join("/etc", "nginx", "nginx.conf"))


# ๐Ÿ”น Subprocess
result = subprocess.run(["echo", "Hello DevOps"], capture_output=True, text=True)
print("Command output:", result.stdout)


# ๐Ÿ”น Pathlib
config_path = Path("/etc") / "nginx" / "nginx.conf"
print("Pathlib path:", config_path)


"""
=======================================================
 ERROR HANDLING
=======================================================
"""

# ๐Ÿ”น Try / Except
try:
    x = 10 / 0
except ZeroDivisionError as e:
    print("Error:", e)
finally:
    print("Cleanup if needed")


# ๐Ÿ”น Custom Exception
class ServerDownError(Exception):
    pass

def check_server(status):
    if not status:
        raise ServerDownError("Server is DOWN!")
    return "Server OK"

print(check_server(True))


"""
=======================================================
 USEFUL BUILT-INS & ITERATION
=======================================================
"""

nums = [10, 20, 30]

# ๐Ÿ”น Enumerate
for i, val in enumerate(nums):
    print(f"Index {i} has value {val}")

# ๐Ÿ”น Zip
names = ["web", "db"]
ips = ["10.0.0.1", "10.0.0.2"]
for n, ip in zip(names, ips):
    print(n, "=>", ip)

# ๐Ÿ”น Comprehension
active_servers = [s for s in servers if "web" in s]
print("Filtered servers:", active_servers)


"""
=======================================================
 WORKING WITH DATA
=======================================================
"""

import json
import csv
import re
from datetime import datetime

# ๐Ÿ”น JSON
data = {"name": "web-01", "ip": "10.0.0.1"}
with open("server.json", "w") as f:
    json.dump(data, f)
print("JSON dump:", json.dumps(data))


# ๐Ÿ”น YAML
# pip install pyyaml
import yaml
with open("server.yaml", "w") as f:
    yaml.dump(data, f)

# ๐Ÿ”น CSV
with open("report.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "ip"])
    writer.writerow(["web-01", "10.0.0.1"])


# ๐Ÿ”น Datetime
now = datetime.now()
print("Current time:", now.strftime("%Y-%m-%d %H:%M:%S"))


# ๐Ÿ”น Regex
log = "Error: Disk full on /dev/sda1"
match = re.search(r"Disk full on (.+)", log)
if match:
    print("Disk issue on:", match.group(1))


"""
=======================================================
 NETWORKING & APIS
=======================================================
"""

import requests

# ๐Ÿ”น Requests
response = requests.get("https://api.github.com")
print("GitHub API status:", response.status_code)


"""
=======================================================
 DEVOPS / SRE SPECIFIC
=======================================================
"""

import logging

# ๐Ÿ”น Logging
logging.basicConfig(level=logging.INFO)
logging.info("Service started successfully.")


# ๐Ÿ”น Argparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--service", help="Service to restart")
args = parser.parse_args([])
print("Service arg:", args.service)


# (Boto3, Kubernetes, Paramiko, Jinja2 would need their libraries and setup)
# Example with Jinja2 template:
from jinja2 import Template
tmpl = Template("server {{ name }} with IP {{ ip }}")
print(tmpl.render(name="web-01", ip="10.0.0.1"))


"""
=======================================================
 TESTING & VALIDATION
=======================================================
"""

# ๐Ÿ”น Assert
cpu = 70
assert cpu < 90, "CPU usage too high!"

# ๐Ÿ”น Unittest
import unittest

class TestServer(unittest.TestCase):
    def test_check_disk(self):
        self.assertEqual(check_disk(70), "Disk usage OK.")

unittest.main(exit=False)

Last updated