Skip to content

Latest commit

 

History

History
165 lines (123 loc) · 4.29 KB

python_interview_guide.md

File metadata and controls

165 lines (123 loc) · 4.29 KB

🐍 Ultimate DevOps & Cloud Interview Guide: Python Edition

Welcome to the Python Interview Guide. This document covers essential libraries, scripting scenarios, and data parsing tasks relevant to DevOps.


📚 Table of Contents

  1. Core Concepts
  2. Common DevOps Libraries
  3. Scripting Scenarios

1. Core Concepts

Q1: Compare List, Set, Tuple and Dictionary?

Type Syntax Ordered? Mutable? Unique? Use Case
List [1, 2, 2] Yes Yes No Ordered sequence (Log lines).
Set {1, 2} No Yes Yes Collecting unique IPs (Deduplication).
Tuple (1, 2) Yes No No Fixed Configuration (Coordinates).
Dict {'k': 'v'} Yes (3.7+) Yes Keys Looking up values (JSON, Environment Variables).

Q2: How do you handle errors in Python scripts?

Philosophy: "Fail Gracefully." Don't let the script crash with a stack trace; print a helpful message.

import sys

try:
    with open("config.yaml") as f:
        content = f.read()
except FileNotFoundError:
    print("Error: config.yaml not found. Please create it.")
    sys.exit(1) # Exit with non-zero status code
except PermissionError:
    print("Error: Permission denied reading config.")
    sys.exit(1)

2. Common DevOps Libraries

Q3: What is Boto3 and how do you use it?

Definition: Boto3 is the AWS SDK for Python. It allows you to create, update, and delete AWS resources programmatically.

Example: List S3 Buckets

import boto3

# Create a client (uses ~/.aws/credentials)
s3 = boto3.client('s3')

response = s3.list_buckets()

print("Buckets:")
for bucket in response['Buckets']:
    print(f"- {bucket['Name']}")

Q4: How do you interact with APIs (Requests)?

Scenario: Check if a website is up.

import requests

try:
    resp = requests.get('https://api.github.com', timeout=5)
    
    if resp.status_code == 200:
        print("API is Up!")
    else:
        print(f"API returned {resp.status_code}")
except requests.exceptions.Timeout:
    print("Request Timed Out.")

3. Scripting Scenarios

Q5: Script - Parse Apache Logs for 404s

Task: "Given a remote log file, find all 404 errors."

import requests

LOG_URL = "https://example.com/access.log"

def analyze_logs():
    r = requests.get(LOG_URL)
    
    # Iterate line by line
    for line in r.text.splitlines():
        # Simple string check (faster than Regex for simple cases)
        if ' 404 ' in line:
            print(f"Broken Link Found: {line}")

if __name__ == "__main__":
    analyze_logs()

Q6: Script - Run a Docker Container using Python

Task: "Use the Docker SDK to run an Nginx container."

import docker

# Connect to local Docker socket
client = docker.from_env()

try:
    print("Pulling Nginx Image...")
    client.images.pull("nginx:latest")
    
    print("Starting Container...")
    container = client.containers.run(
        "nginx:latest",
        detach=True,
        ports={'80/tcp': 8080},
        name="my-web-server"
    )
    print(f"Started container {container.short_id}")
    
except docker.errors.APIError as e:
    print(f"Docker Error: {e}")

Q7: Script - Extract Data from JSON

Task: "Get the ID of all Running instances from this JSON."

import json

raw_response = '''
{
  "instances": [
    {"id": "i-123", "state": "running", "type": "t2.micro"},
    {"id": "i-456", "state": "stopped", "type": "m5.large"},
    {"id": "i-789", "state": "running", "type": "t2.micro"}
  ]
}
'''

data = json.loads(raw_response)

# List Comprehension (Pythonic way)
running_ids = [
    inst['id'] 
    for inst in data['instances'] 
    if inst['state'] == 'running'
]

print(f"Running Instances: {running_ids}")