Scenario-Based Python Interview Questions for DevOps (2027)
61 scenario-based Python interview questions for DevOps with tested Python 3.12 code: subprocess, boto3, requests, log parsing, packaging and pytest.
Scenario-based Python interview questions for DevOps roles test whether you can write automation that fails safely: running commands with subprocess, calling AWS with boto3, calling APIs with requests, parsing logs, handling errors, and packaging and testing your scripts. This page has 61 questions with answers and runnable Python 3.12 code, grouped by experience level.
Every code sample was run on Python 3.12, and the AWS examples were tested against the moto library instead of a real account.
Key takeaways
- Freshers are asked about virtual environments, reading files and environment variables, exceptions, exit codes, argparse and logging.
- Experienced candidates are expected to write subprocess calls with
check=Trueand a timeout, HTTP calls with timeouts and retries, and boto3 code that paginates and handlesClientError. - Scenario questions focus on what goes wrong in production: scripts that hang, miss data after the first page, hit API throttling, leak secrets into logs, or report success after a failure.
- Python 3.12 removed
distutilsandimp, deprecateddatetime.utcnow(), and stopped installing setuptools into new virtual environments. Old scripts can break on upgrade. - Interviewers look for safe defaults: dry-run first, idempotent actions, non-zero exit codes on failure and tests that do not touch real infrastructure.
How to use this guide
Each answer opens with the short reply you can give in an interview, then the detail and code an interviewer may ask you to write. If you are also preparing for Linux, Docker, Kubernetes and CI/CD rounds, use our 200+ DevOps interview questions guide alongside this one.
| Your experience | Read first | Then practise |
|---|---|---|
| Fresher or career switcher | Questions 1 to 18 | A CLI script with argparse, logging and a correct exit code |
| 1 to 4 years | Questions 19 to 40 | A boto3 report script with pagination, retries and a dry-run flag |
| Senior or lead | Questions 41 to 48 | Package a tool with pyproject.toml and test it in CI with mocks |
| Everyone with work experience | Questions 49 to 61 (scenarios) | Explain symptom, cause, fix and prevention for each scenario aloud |
Python interview questions for DevOps freshers
1. Why do DevOps engineers use Python when Bash already exists?
Bash is the better choice for short glue scripts that chain a few commands. Python is easier once a script needs data structures, JSON or YAML, HTTP calls, cloud SDKs, error handling or tests.
| Task | Bash | Python |
|---|---|---|
| Chain three commands, check exit codes | Good fit | Works, more code |
| Parse JSON or YAML | Needs jq or yq | Built in (json) or PyYAML |
| Call AWS APIs with pagination and retries | AWS CLI plus loops | boto3 paginators and retry config |
| Unit tests | Possible (bats), less common | pytest, mocks, fixtures |
| Cross-platform scripts | Linux and macOS | Linux, macOS and Windows |
For a wider comparison, see scripting languages used in DevOps.
2. What is a virtual environment and why should every script use one?
A virtual environment is an isolated directory with its own Python interpreter link and installed packages. It keeps one project's dependencies from breaking another project or the operating system's Python.
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip freeze > requirements.lock.txt # exact versions that worked
deactivate
Since Python 3.12, venv no longer pre-installs setuptools, so install it explicitly if a build needs it.
3. What is the difference between requirements.txt, pyproject.toml and a lock file?
requirements.txt is a list of packages for pip to install. pyproject.toml is the standard project file: it holds the package name, version, Python requirement, dependencies and build backend. A lock file (for example the output of pip freeze) records the exact versions that were installed, so CI and production get the same set. For a script, a pinned requirements file is enough. For a tool you distribute, use pyproject.toml (see question 41).
4. How do you read environment variables in a script?
Use os.environ.get() with a default for optional settings and os.environ[...] for required ones, so a missing value fails at startup with a clear message instead of halfway through a deployment.
import os
import sys
region = os.environ.get("AWS_REGION", "ap-south-1") # optional, has a default
try:
db_url = os.environ["DATABASE_URL"] # required, no default
except KeyError:
sys.exit("DATABASE_URL is not set")
5. Which built-in data structures do you use most in automation scripts?
| Type | Typical DevOps use |
|---|---|
list | Ordered hosts, instance IDs, command arguments |
dict | Parsed JSON or YAML, tags, lookups by ID |
set | Differences between two inventories (desired minus actual) |
tuple | Fixed records such as (host, port) |
collections.Counter | Counting status codes, error types, IPs |
Dictionary and set lookups are O(1) on average, which is why you convert a large list to a set before checking membership in a loop.
6. How do you read a very large log file without running out of memory?
Iterate over the file object line by line. Python reads it in buffered chunks, so memory stays flat whether the file is 10 MB or 20 GB. Avoid f.read() and f.readlines() on big files because they load everything. Question 22 shows a full log parser built this way.
7. What does the with statement do?
with uses a context manager that sets something up and always cleans it up, even if an exception is raised. For files it closes the file; for locks it releases the lock; for subprocess.Popen it waits for the process. It replaces try/finally blocks you would otherwise write by hand.
8. How should you handle exceptions in an automation script?
Catch the specific exceptions you expect and can act on, let unexpected ones fail loudly, and keep the try block small.
try: only the line that can fail.except SomeError: handle or translate a known failure. Avoid a bareexcept:, which also catchesKeyboardInterruptandSystemExit.else: code that runs only if nothing failed.finally: cleanup that must always run.
Use logging.exception() inside an except block to record the traceback.
9. What does if __name__ == "__main__" do?
The block runs only when the file is executed directly, not when it is imported. That lets you import functions from your script into tests without triggering the real work, such as deleting files or calling AWS.
10. How do you parse JSON and YAML safely?
Use json.loads() or json.load() for JSON and catch json.JSONDecodeError, which tells you the line and column. For YAML use PyYAML's yaml.safe_load(). Plain yaml.load() with an unsafe loader can construct arbitrary Python objects from a crafted file. Question 35 shows a config loader with validation.
11. Why use pathlib instead of os.path?
pathlib.Path gives you path objects with methods: / to join, .exists(), .read_text(), .glob(), .rglob() and .stat(). Code is shorter and works on Linux and Windows without string joins. os.path still works, but new code usually uses pathlib.
12. How do you accept command-line arguments?
Use the standard library argparse module. It gives you typed arguments, defaults, --help output and an error message with exit code 2 for bad input. Add a --dry-run or --apply flag to any script that changes something (question 23).
13. Why use logging instead of print?
logging gives you levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), timestamps, logger names and handlers that can write to stdout, files or a log collector. You can turn debug output on without editing code. Pass values as arguments, log.info("deleted %s", path), so formatting only happens if the message is emitted. Print is fine for a script's actual output, such as a report.
14. How do exit codes work in Python scripts?
A script exits with 0 when it finishes normally and 1 when an unhandled exception ends it. sys.exit(n) raises SystemExit with code n; sys.exit("message") prints the message to stderr and exits with 1. CI systems, cron wrappers and Kubernetes Jobs read this code, so a script that catches every error and exits 0 hides failures. A common pattern is raise SystemExit(main()) where main() returns an int.
15. What is the GIL and when does it matter for DevOps scripts?
The Global Interpreter Lock in CPython lets only one thread run Python bytecode at a time. Threads still help for I/O-bound work such as HTTP calls, SSH sessions and AWS API calls, because the lock is released while waiting. For CPU-bound work such as compressing or hashing many files, use multiprocessing or concurrent.futures.ProcessPoolExecutor. Python 3.13 added an experimental free-threaded build, but standard Python 3.12 has the GIL.
16. Why is a mutable default argument a bug?
Default values are created once, when the function is defined. A list default is shared between calls, so data leaks from one call into the next.
def add_host(host, hosts=[]): # bug: one list shared by every call
hosts.append(host)
return hosts
def add_host_fixed(host, hosts=None):
if hosts is None:
hosts = []
hosts.append(host)
return hosts
print(add_host("web1"), add_host("web2")) # ['web1', 'web2'] ['web1', 'web2']
print(add_host_fixed("web1"), add_host_fixed("web2")) # ['web1'] ['web2']
17. How do you pin and upgrade dependencies?
Pin exact or compatible versions (requests==2.32.3 or requests~=2.32) so a new release cannot change behaviour without a code change. Upgrade on purpose: bump versions in a branch, run tests, then merge. Tools such as Dependabot or Renovate can open those pull requests. Run pip check to find broken dependency combinations.
18. What is the difference between a module, a package and a library?
A module is one .py file. A package is a directory of modules, usually with an __init__.py. A library, or distribution, is what you install with pip; it can contain several packages. The name you install and the name you import can differ: you install PyYAML but import yaml.
Python automation questions for experienced DevOps engineers
19. How do you run a shell command from Python safely?
Use subprocess.run() with the command as a list, check=True so a non-zero exit raises, a timeout so it cannot hang, and capture_output=True, text=True to get strings back.
import logging
import subprocess
import sys
log = logging.getLogger(__name__)
def run(cmd: list[str], timeout: int = 60) -> str:
"""Run a command without a shell and return its stdout."""
try:
result = subprocess.run(
cmd, capture_output=True, text=True, check=True, timeout=timeout
)
except FileNotFoundError:
log.error("command not found: %s", cmd[0])
raise
except subprocess.TimeoutExpired:
log.error("timed out after %ss: %s", timeout, cmd)
raise
except subprocess.CalledProcessError as exc:
log.error("exit %s from %s: %s", exc.returncode, cmd, exc.stderr.strip())
raise
return result.stdout
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
print(run([sys.executable, "--version"]).strip())
Three different failures are handled separately: the binary is missing, the command took too long, or it ran and failed. Each needs a different fix.
20. Why should you avoid shell=True?
With shell=True, the string is passed to /bin/sh, so any user input in it can inject extra commands (; rm -rf /). A list of arguments is passed directly to the program with no shell parsing. If you really need shell features such as pipes or globbing, build them in Python or quote every variable with shlex.quote(). Python's own documentation warns about shell injection for this reason.
21. How do you stream the output of a long-running command?
subprocess.run() returns only when the command finishes. For a build or a migration where you want to see progress, use Popen and read stdout line by line.
import subprocess
import sys
cmd = [sys.executable, "-c", "for i in range(3): print('step', i, flush=True)"]
with subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
) as proc:
for line in proc.stdout:
print("build:", line.rstrip())
if proc.returncode != 0:
sys.exit(f"build failed with exit code {proc.returncode}")
22. Write a script that counts HTTP status codes and finds the paths with the most 5xx errors.
Read the access log line by line, match each line with a compiled regular expression and count with collections.Counter. Skip lines that do not match instead of crashing on them.
import re
import sys
from collections import Counter
LINE = re.compile(
r'(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] "(?P<method>\S+) (?P<path>\S+) [^"]*" '
r"(?P<status>\d{3}) (?P<size>\d+|-)"
)
def summarize(path: str) -> tuple[Counter, Counter]:
statuses, error_paths = Counter(), Counter()
with open(path, encoding="utf-8", errors="replace") as fh:
for line in fh: # one line at a time, so a 20 GB file is fine
m = LINE.match(line)
if not m:
continue
statuses[m["status"]] += 1
if m["status"].startswith("5"):
error_paths[m["path"]] += 1
return statuses, error_paths
if __name__ == "__main__":
statuses, errors = summarize(sys.argv[1])
print(dict(statuses))
for path, count in errors.most_common(5):
print(f"{count:6d} {path}")
The errors="replace" argument stops one bad byte in a log from raising UnicodeDecodeError halfway through.
23. Write a cleanup script that deletes old files safely.
Default to a dry run, log every file it would delete, and delete only when the operator passes --apply.
import argparse
import logging
import time
from pathlib import Path
log = logging.getLogger("cleanup")
def old_files(root: Path, pattern: str, days: int):
cutoff = time.time() - days * 86400
for path in root.rglob(pattern):
if path.is_file() and path.stat().st_mtime < cutoff:
yield path
def main() -> int:
parser = argparse.ArgumentParser(description="Delete old log files")
parser.add_argument("root", type=Path)
parser.add_argument("--pattern", default="*.log.gz")
parser.add_argument("--days", type=int, default=14)
parser.add_argument("--apply", action="store_true", help="actually delete")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
count = 0
for path in old_files(args.root, args.pattern, args.days):
count += 1
if args.apply:
path.unlink(missing_ok=True)
log.info("deleted %s", path)
else:
log.info("would delete %s", path)
log.info("%d file(s) matched", count)
return 0
if __name__ == "__main__":
raise SystemExit(main())
Interviewers often follow up with "what if two runs overlap?" unlink(missing_ok=True) makes the delete idempotent, and question 59 shows a lock.
24. How do you make HTTP calls with requests reliable?
Always pass a timeout, retry only on transient failures, and call raise_for_status() so 4xx and 5xx responses become exceptions.
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def make_session() -> requests.Session:
retry = Retry(
total=5,
backoff_factor=0.5, # first retry at once, then waits of 1s, 2s, 4s ...
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "HEAD", "PUT", "DELETE"], # idempotent only
respect_retry_after_header=True,
)
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
session.mount("http://", HTTPAdapter(max_retries=retry))
return session
def get_json(session: requests.Session, url: str) -> dict:
resp = session.get(url, timeout=(3.05, 10)) # (connect, read) seconds
resp.raise_for_status()
return resp.json()
requests has no default timeout, so a call without one can wait forever. The Retry object comes from urllib3, which requests uses underneath. Retrying POST is left out on purpose because a repeated POST can create a duplicate resource.
25. How do you check many endpoints quickly?
HTTP checks spend most of their time waiting on the network, so threads work well. ThreadPoolExecutor.map() runs the checks in parallel and returns results in input order.
import sys
from concurrent.futures import ThreadPoolExecutor
import requests
URLS = [
"https://example.com/healthz",
"https://example.org/healthz",
]
def check(url: str) -> tuple[str, bool, str]:
try:
resp = requests.get(url, timeout=5)
return url, resp.ok, str(resp.status_code)
except requests.RequestException as exc:
return url, False, type(exc).__name__
def main() -> int:
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(check, URLS))
for url, ok, detail in results:
print(f"{'OK ' if ok else 'FAIL'} {detail:>20} {url}")
return 0 if all(ok for _, ok, _ in results) else 1
if __name__ == "__main__":
sys.exit(main())
The exit code is 1 if any check failed, so the script can gate a pipeline or a cron alert.
26. How does boto3 find AWS credentials?
boto3 searches a fixed chain: parameters passed to the client, environment variables, the shared credentials and config files (including profiles, SSO and assume-role settings), container credentials on ECS, and the EC2 instance metadata service for an instance role. In production, use an IAM role (instance profile, ECS task role, EKS IRSA or Pod Identity, or Lambda execution role) so no access keys live in code or on disk.
27. What is the difference between a boto3 client and a resource?
A client maps one-to-one to AWS API operations and returns dictionaries. A resource is an object-oriented layer (for example s3.Bucket("name").objects.all()). The boto3 documentation says the SDK team does not plan to add new features to the resources interface, so new code should use clients. Clients also cover every service, while resources cover only some.
28. Write a boto3 script that finds running instances by tag and stops them.
Use a paginator, filter on the server side, and use DryRun=True to check permissions before acting.
import logging
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
log = logging.getLogger(__name__)
CONFIG = Config(retries={"total_max_attempts": 10, "mode": "standard"})
def running_instances_with_tag(ec2, key: str, value: str) -> list[str]:
paginator = ec2.get_paginator("describe_instances")
pages = paginator.paginate(
Filters=[
{"Name": f"tag:{key}", "Values": [value]},
{"Name": "instance-state-name", "Values": ["running"]},
]
)
return [
inst["InstanceId"]
for page in pages
for reservation in page["Reservations"]
for inst in reservation["Instances"]
]
def stop_instances(ec2, ids: list[str], dry_run: bool = True) -> None:
if not ids:
log.info("nothing to stop")
return
try:
ec2.stop_instances(InstanceIds=ids, DryRun=dry_run)
except ClientError as exc:
code = exc.response["Error"]["Code"]
if code == "DryRunOperation":
log.info("dry run OK, would stop %s", ids)
return
log.error("stop failed (%s): %s", code, exc)
raise
log.info("stopping %s", ids)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
ec2 = boto3.client("ec2", region_name="ap-south-1", config=CONFIG)
ids = running_instances_with_tag(ec2, "env", "dev")
stop_instances(ec2, ids, dry_run=True)
With DryRun=True, EC2 answers with a DryRunOperation error when you have permission and UnauthorizedOperation when you do not, so you can test IAM policies safely.
29. How do you handle AWS API errors and throttling in boto3?
Service errors arrive as botocore.exceptions.ClientError. Read exc.response["Error"]["Code"] to branch on codes such as ThrottlingException, AccessDenied or NoSuchKey. For throttling, configure botocore's retry behaviour instead of writing your own loop: Config(retries={"total_max_attempts": 10, "mode": "standard"}). Standard mode retries throttling and transient errors with exponential backoff and is the same across AWS SDKs. The default is still legacy mode, so set the mode explicitly. Adaptive mode adds client-side rate limiting on top of standard mode but is marked experimental. In a Config object, max_attempts counts retries only, while total_max_attempts includes the first request. Network problems raise other botocore exceptions such as EndpointConnectionError.
30. Write a script that finds and deletes S3 objects older than N days.
from datetime import datetime, timedelta, timezone
import boto3
def stale_keys(s3, bucket: str, prefix: str, days: int) -> list[str]:
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
keys = []
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
for obj in page.get("Contents", []): # "Contents" is missing on empty pages
if obj["LastModified"] < cutoff:
keys.append(obj["Key"])
return keys
def delete_keys(s3, bucket: str, keys: list[str]) -> int:
deleted = 0
for i in range(0, len(keys), 1000): # DeleteObjects takes at most 1,000 keys
batch = [{"Key": k} for k in keys[i : i + 1000]]
resp = s3.delete_objects(Bucket=bucket, Delete={"Objects": batch, "Quiet": True})
for err in resp.get("Errors", []):
print("failed:", err["Key"], err["Code"])
deleted += len(batch) - len(resp.get("Errors", []))
return deleted
Two details interviewers check: Contents is missing from a page when nothing matches, and delete_objects accepts at most 1,000 keys per request. LastModified is timezone-aware, so compare it with an aware datetime. For a permanent rule, an S3 Lifecycle configuration does this without any script.
31. How do you read a secret from AWS Secrets Manager?
import json
import boto3
from botocore.exceptions import ClientError
def get_db_credentials(secret_id: str, region: str = "ap-south-1") -> dict:
client = boto3.client("secretsmanager", region_name=region)
try:
resp = client.get_secret_value(SecretId=secret_id)
except ClientError as exc:
if exc.response["Error"]["Code"] == "ResourceNotFoundException":
raise SystemExit(f"secret {secret_id} not found") from exc
raise
return json.loads(resp["SecretString"])
Never log the returned value. Give the script's IAM role secretsmanager:GetSecretValue on that one secret only, and kms:Decrypt if the secret uses a customer managed key.
32. Write a Lambda function in Python that reacts to S3 uploads.
import json
import logging
import os
from urllib.parse import unquote_plus
import boto3
log = logging.getLogger()
log.setLevel(logging.INFO)
sns = boto3.client("sns") # created once per execution environment and reused
TOPIC_ARN = os.environ.get("TOPIC_ARN", "")
def lambda_handler(event, context):
records = event.get("Records", [])
for record in records:
bucket = record["s3"]["bucket"]["name"]
key = unquote_plus(record["s3"]["object"]["key"]) # keys arrive URL-encoded
log.info("new object s3://%s/%s", bucket, key)
if TOPIC_ARN:
sns.publish(TopicArn=TOPIC_ARN, Subject="New upload",
Message=json.dumps({"bucket": bucket, "key": key}))
return {"processed": len(records)}
Clients created outside the handler are reused while the execution environment stays warm. Object keys in S3 event notifications are URL-encoded, so unquote_plus is needed for keys with spaces or special characters. Our AWS Lambda and serverless guide covers the execution model.
33. How do you write a state file so a crash cannot leave it half written?
Write to a temporary file in the same directory, flush and fsync it, then rename it over the target with os.replace(). The rename is atomic on POSIX file systems when both paths are on the same file system, so readers see either the old file or the new one.
import json
import os
import tempfile
from pathlib import Path
def write_json_atomic(path: Path, data: dict) -> None:
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2)
fh.flush()
os.fsync(fh.fileno())
os.replace(tmp, path) # atomic when tmp and path are on the same filesystem
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
if __name__ == "__main__":
target = Path("inventory.json")
write_json_atomic(target, {"hosts": ["web1", "web2"]})
print(target.read_text())
34. How do you produce structured (JSON) logs?
Log collectors such as Loki, Elasticsearch or CloudWatch Logs Insights can filter on fields when each line is a JSON object. A small custom formatter is enough; no extra library is required.
import json
import logging
import sys
from datetime import datetime, timezone
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
entry = {
"ts": datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat(),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
}
if record.exc_info:
entry["exc"] = self.formatException(record.exc_info)
return json.dumps(entry)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler])
log = logging.getLogger("deploy")
log.info("rollout started for %s", "payments-api")
try:
1 / 0
except ZeroDivisionError:
log.exception("rollout step failed")
35. How do you load and validate a YAML config file?
Load with safe_load, check the shape you expect, and convert entries into typed objects so a typo fails at startup.
import os
from dataclasses import dataclass
from pathlib import Path
import yaml # PyYAML
@dataclass(frozen=True)
class Service:
name: str
replicas: int
def load_services(path: Path) -> list[Service]:
with path.open(encoding="utf-8") as fh:
raw = yaml.safe_load(fh) # never yaml.load() without a safe Loader
if not isinstance(raw, dict) or "services" not in raw:
raise ValueError(f"{path}: missing 'services' key")
return [Service(s["name"], int(s["replicas"])) for s in raw["services"]]
REGION = os.environ.get("AWS_REGION", "ap-south-1") # optional, with a default
API_TOKEN = os.environ.get("API_TOKEN") # secret: from the environment, never the file
if __name__ == "__main__":
for svc in load_services(Path("config.yaml")):
print(svc)
Keep secrets out of the config file; read them from the environment or a secrets manager (question 31).
36. How do you back up and restore a directory with tarfile safely?
import tarfile
from datetime import datetime, timezone
from pathlib import Path
def make_backup(src: Path, dest_dir: Path) -> Path:
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
archive = dest_dir / f"{src.name}-{stamp}.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
tar.add(src, arcname=src.name)
return archive
def restore(archive: Path, dest: Path) -> None:
with tarfile.open(archive, "r:gz") as tar:
tar.extractall(dest, filter="data") # rejects absolute paths and ../ entries
if __name__ == "__main__":
src = Path("demo_conf")
src.mkdir(exist_ok=True)
(src / "app.ini").write_text("[app]\nport = 8080\n")
out = make_backup(src, Path("."))
restore(out, Path("restored"))
print(out.name, (Path("restored") / "demo_conf" / "app.ini").exists())
Extraction filters arrived in Python 3.12 (and in security releases of older versions). filter="data" rejects absolute paths, .. traversal and special files, which protects you from a malicious archive. Python 3.14 makes "data" the default.
37. How do you make a long-running Python worker shut down cleanly in a container?
Kubernetes and Docker send SIGTERM first and SIGKILL after a grace period (30 seconds by default in Kubernetes). Handle SIGTERM, stop taking new work, finish the current job and exit.
import logging
import signal
import threading
log = logging.getLogger("worker")
stop = threading.Event()
def handle_signal(signum, frame):
log.info("received %s, finishing current job", signal.Signals(signum).name)
stop.set()
def main() -> None:
logging.basicConfig(level=logging.INFO)
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
while not stop.is_set():
# process one message from the queue here
stop.wait(timeout=1)
log.info("clean shutdown")
if __name__ == "__main__":
main()
Run Python as PID 1 with the exec form of CMD (CMD ["python", "worker.py"]). With the shell form, /bin/sh is PID 1 and may not forward the signal.
38. When would you use asyncio in a DevOps script?
Use asyncio when a script waits on hundreds or thousands of network operations at once, such as port checks or API calls with an async client. Start it with asyncio.run(). The older pattern asyncio.get_event_loop().run_until_complete() emits a DeprecationWarning in Python 3.12 when no loop is running.
import asyncio
async def port_open(host: str, port: int, timeout: float = 3.0) -> tuple[str, int, bool]:
try:
_, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout)
except (OSError, asyncio.TimeoutError):
return host, port, False
writer.close()
await writer.wait_closed()
return host, port, True
async def main() -> None:
targets = [("127.0.0.1", 22), ("127.0.0.1", 5432), ("127.0.0.1", 6379)]
results = await asyncio.gather(*(port_open(h, p) for h, p in targets))
for host, port, ok in results:
print(f"{host}:{port} {'open' if ok else 'closed'}")
if __name__ == "__main__":
asyncio.run(main())
For a few dozen calls, a thread pool (question 25) is simpler and works with libraries such as requests and boto3, which are not async.
39. How do you write custom exceptions and keep the original error?
Define one exception type for your tool's failures and raise it with from exc. The message stays readable for operators and the original exception is kept in __cause__ for the traceback.
import json
from pathlib import Path
class DeployConfigError(Exception):
"""Raised when a deployment manifest cannot be used."""
def load_manifest(path: Path) -> dict:
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise DeployConfigError(f"manifest not found: {path}") from exc
except json.JSONDecodeError as exc:
raise DeployConfigError(
f"{path}: invalid JSON at line {exc.lineno}, column {exc.colno}"
) from exc
if __name__ == "__main__":
bad = Path("bad.json")
bad.write_text('{"image": "app:1.4",}')
try:
load_manifest(bad)
except DeployConfigError as err:
print("error:", err)
print("caused by:", repr(err.__cause__))
40. Write a retry decorator with exponential backoff and jitter.
Retry only exceptions that are likely to be temporary, cap the delay, and add random jitter so many clients do not retry at the same moment.
import functools
import logging
import random
import time
log = logging.getLogger(__name__)
def retry(exceptions: tuple[type[Exception], ...], attempts: int = 5,
base: float = 0.5, cap: float = 30.0):
"""Retry with exponential backoff and full jitter."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, attempts + 1):
try:
return func(*args, **kwargs)
except exceptions as exc:
if attempt == attempts:
raise
delay = random.uniform(0, min(cap, base * 2 ** attempt))
log.warning("%s failed (%s), retry %d/%d in %.1fs",
func.__name__, exc, attempt, attempts - 1, delay)
time.sleep(delay)
return wrapper
return decorator
@retry((ConnectionError, TimeoutError), attempts=4)
def fetch_inventory() -> dict:
... # call an API that sometimes drops connections
Use it only around idempotent operations. For HTTP and AWS calls, prefer the built-in retry support from questions 24 and 29.
Packaging, testing and Python 3.12 questions (senior)
41. How do you package an internal CLI tool so others can install it?
Create a pyproject.toml with a [project.scripts] entry point, use a src/ layout, build a wheel and install it with pipx or pip in a virtual environment.
cat > pyproject.toml <<'EOF'
[build-system]
requires = ["setuptools>=69"]
build-backend = "setuptools.build_meta"
[project]
name = "opsctl"
version = "0.3.0"
requires-python = ">=3.12"
dependencies = ["boto3>=1.34", "requests>=2.32", "PyYAML>=6.0"]
[project.optional-dependencies]
dev = ["pytest>=8", "moto[s3,ec2]>=5"]
[project.scripts]
opsctl = "opsctl.cli:main"
EOF
# layout
# opsctl/
# pyproject.toml
# src/opsctl/__init__.py
# src/opsctl/cli.py (defines main())
# tests/test_cli.py
python -m pip install -e ".[dev]" # editable install for development
opsctl --help # console script created from [project.scripts]
python -m pip install build
python -m build # writes dist/*.whl and dist/*.tar.gz
pipx install dist/opsctl-0.3.0-py3-none-any.whl # isolated install for operators
The src/ layout stops setuptools from picking up stray top-level folders (for example a virtual environment inside the project) and makes tests run against the installed package.
42. What changed in Python 3.12 that can break older DevOps scripts?
| Change in 3.12 | Symptom | Fix |
|---|---|---|
distutils removed | ModuleNotFoundError: No module named 'distutils' | Use setuptools or packaging; for LooseVersion use packaging.version.Version |
imp removed | ModuleNotFoundError: No module named 'imp' | Use importlib |
setuptools not pre-installed by venv | Builds fail inside a fresh venv | Install setuptools explicitly or use python -m build |
datetime.utcnow() deprecated | DeprecationWarning | datetime.now(timezone.utc) |
| Invalid escape sequences now a SyntaxWarning | Warnings for regex strings such as "\d" | Use raw strings: r"\d" |
| tarfile extraction filters added | 3.12 warns when extracting without a filter | Pass filter="data" |
from datetime import datetime, timezone
# datetime.utcnow() is deprecated since Python 3.12 and returns a naive datetime
now = datetime.now(timezone.utc)
print(now.isoformat()) # 2026-11-06T09:15:42.123456+00:00
43. How do you unit test code that calls subprocess?
Replace subprocess.run with a fake using pytest's monkeypatch fixture, and return a CompletedProcess. The test runs in milliseconds and does not need git, kubectl or terraform installed.
import subprocess
import s01_run
def test_run_uses_subprocess(monkeypatch):
calls = []
def fake_run(cmd, **kwargs):
calls.append(cmd)
return subprocess.CompletedProcess(cmd, 0, stdout="v1.2.3\n", stderr="")
monkeypatch.setattr(s01_run.subprocess, "run", fake_run)
assert s01_run.run(["git", "describe"]).strip() == "v1.2.3"
assert calls == [["git", "describe"]]
Keep a few real-process tests too, for timeouts and non-zero exits:
import subprocess
import sys
import pytest
from s01_run import run
def test_run_returns_stdout():
assert run([sys.executable, "-c", "print('hi')"]).strip() == "hi"
def test_run_raises_on_non_zero_exit():
with pytest.raises(subprocess.CalledProcessError):
run([sys.executable, "-c", "import sys; sys.exit(3)"])
def test_run_times_out():
with pytest.raises(subprocess.TimeoutExpired):
run([sys.executable, "-c", "import time; time.sleep(5)"], timeout=1)
def test_run_missing_binary():
with pytest.raises(FileNotFoundError):
run(["definitely-not-a-real-binary-xyz"])
44. How do you test boto3 code without a real AWS account?
Use moto, which fakes AWS services in memory. Version 5 uses a single mock_aws decorator. botocore's built-in Stubber is the other option when you want to assert exact API calls and responses.
import boto3
from moto import mock_aws
from s08_s3 import delete_keys, stale_keys
@mock_aws
def test_stale_keys_and_delete():
s3 = boto3.client("s3", region_name="us-east-1")
s3.create_bucket(Bucket="demo-app-logs")
s3.put_object(Bucket="demo-app-logs", Key="app/old.log", Body=b"x")
# every object moto creates is "new", so days=-1 makes all of them stale
keys = stale_keys(s3, "demo-app-logs", "app/", days=-1)
assert keys == ["app/old.log"]
assert delete_keys(s3, "demo-app-logs", keys) == 1
assert stale_keys(s3, "demo-app-logs", "app/", days=-1) == []
45. Which pytest features do you use most for automation code?
tmp_path gives each test its own temporary directory, monkeypatch changes environment variables and attributes for one test, and parametrize runs one test with many inputs.
import pytest
def parse_size(text: str) -> int:
units = {"K": 1024, "M": 1024**2, "G": 1024**3}
text = text.strip().upper()
if text and text[-1] in units:
return int(float(text[:-1]) * units[text[-1]])
return int(text)
@pytest.mark.parametrize(
"text, expected",
[("512", 512), ("1K", 1024), ("1.5M", 1572864), (" 2g ", 2147483648)],
)
def test_parse_size(text, expected):
assert parse_size(text) == expected
def test_parse_size_rejects_garbage():
with pytest.raises(ValueError):
parse_size("lots")
Testing the log parser from question 22 with tmp_path looks like this:
from s03_log import summarize
def test_summarize(tmp_path):
log = tmp_path / "access.log"
log.write_text(
'1.1.1.1 - - [06/Nov/2026:10:00:01 +0530] "GET /a HTTP/1.1" 200 5 "-" "x"\n'
'1.1.1.1 - - [06/Nov/2026:10:00:02 +0530] "GET /pay HTTP/1.1" 502 0 "-" "x"\n'
"not a log line\n"
)
statuses, errors = summarize(str(log))
assert statuses == {"200": 1, "502": 1}
assert errors["/pay"] == 1
46. How do you run Python tests in a CI pipeline?
Pin the Python version, cache pip downloads, install the project with its dev extras and run pytest. A GitHub Actions example:
name: tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- run: python -m pip install -e ".[dev]"
- run: python -m pytest -q
Add a linter such as Ruff or flake8 and a type checker such as mypy as separate steps so each failure is easy to read.
47. How do you keep secrets out of logs?
Do not log secret values in the first place: log the name of the secret, never its content. As a safety net, add a logging filter that masks known patterns.
import logging
import re
class RedactSecrets(logging.Filter):
PATTERN = re.compile(r"(?i)(password|token|secret|api[_-]?key)=\S+")
def filter(self, record: logging.LogRecord) -> bool:
record.msg = self.PATTERN.sub(r"\1=***", record.getMessage())
record.args = None
return True
logging.basicConfig(level=logging.INFO)
for handler in logging.getLogger().handlers:
handler.addFilter(RedactSecrets())
logging.getLogger("deploy").info("connecting with token=%s", "abc123")
# INFO:deploy:connecting with token=***
Also avoid printing the full environment, and avoid passing secrets as command-line arguments, because other users on the host can read them from the process list.
48. How do you decide between threads, processes and asyncio?
| Workload | Use | Example |
|---|---|---|
| Waiting on network or disk, tens of tasks | ThreadPoolExecutor | Health checks, boto3 calls across regions |
| Waiting on network, thousands of tasks | asyncio with async libraries | Port scans, async HTTP clients |
| CPU-heavy work | ProcessPoolExecutor | Compressing or hashing many files, parsing many large logs |
boto3 clients are thread-safe for most uses, but sessions and resources are not; create one client per thread or share one client created up front.
Scenario-based Python questions for DevOps
49. A nightly Python job sometimes never finishes and the next run piles up. What do you check?
Look for calls with no timeout: requests.get() without timeout=, subprocess.run() without timeout=, and database or socket connections without one. Add timeouts everywhere, add a lock so overlapping runs exit (question 59), and add an overall limit in the scheduler, such as timeout in a systemd unit or activeDeadlineSeconds on a Kubernetes Job.
50. The script works on your laptop but fails in CI with ModuleNotFoundError. Why?
Usually the package is installed on your laptop globally or in another environment but is missing from requirements.txt or pyproject.toml. Other causes are a different Python version in CI, an install name that differs from the import name (PyYAML versus yaml), or a module removed in 3.12 such as distutils. Fix it by creating a fresh venv locally, installing only from the declared dependencies and running the tests there.
51. Your boto3 report shows exactly 1,000 S3 objects, but the bucket has far more. What is wrong?
A single list_objects_v2 call returns at most 1,000 keys. Many other list and describe calls are paginated too. Use client.get_paginator(...) and loop over every page, as in questions 28 and 30. Paginators handle the continuation token for you.
52. A script that tags thousands of resources fails with ThrottlingException. How do you fix it?
Turn on botocore retries in standard or adaptive mode with a higher total_max_attempts, batch operations where the API accepts several IDs per call, and reduce parallelism. If the job must finish faster, ask whether the API has a bulk alternative or whether a service quota increase is available. Log the throttled call count so you can see whether the change helped.
53. A cleanup script deleted files that were still needed. How do you prevent this next time?
- Make dry-run the default and require an explicit
--applyflag. - Restrict the scope: an allowed root directory, a file pattern and a minimum age.
- Log every deletion with the full path so you can see exactly what happened.
- Test the selection logic with pytest and
tmp_pathbefore it touches real data. - For cloud resources, prefer moving to a quarantine location or using versioning before a hard delete.
54. Your log parser takes an hour on a 20 GB file. How do you speed it up?
First measure with cProfile or py-spy to see where time goes. Common fixes: compile the regex once outside the loop, skip lines early with a cheap check such as if " 5" not in line before running the regex, avoid building large lists, and process several files in parallel with ProcessPoolExecutor because parsing is CPU-bound. If the log is already in a central system, query it there instead of downloading it.
55. A database password appeared in the CI log from a Python step. What do you do?
Rotate the password first, because anyone with access to the log may have it. Then find the cause: a debug log of the full config, an exception message that included a connection string, or a secret passed on the command line. Remove it from the code, add a redaction filter (question 47), and use the CI system's masked secrets. Delete or restrict the log if your CI platform allows it.
56. Pods running your Python worker take 30 seconds to stop and lose in-flight work. Why?
The process is not handling SIGTERM, so Kubernetes waits for the grace period and then sends SIGKILL. Check whether Python is PID 1 (exec form CMD) and add a SIGTERM handler that finishes the current job (question 37). If jobs take longer than 30 seconds, raise terminationGracePeriodSeconds.
57. After upgrading to Python 3.12 you see "SyntaxWarning: invalid escape sequence". What is it?
A regular string contains a backslash sequence Python does not recognise, such as "\d" in a regex. Earlier versions raised a DeprecationWarning that was hidden by default; 3.12 shows a SyntaxWarning. The fix is a raw string:
import re
# Python 3.12 warns about "\d" in a normal string: SyntaxWarning: invalid escape sequence '\d'
pattern = re.compile(r"ERROR \[(\d+)\]") # raw string: the backslashes reach re untouched
print(pattern.search("2026-11-06 ERROR [504] upstream timeout").group(1))
58. pip install fails with "externally-managed-environment" on a Linux server. What does it mean?
The distribution marks its system Python as managed by the OS package manager (PEP 668), so pip refuses to install into it. Recent Debian and Ubuntu releases do this. Create a virtual environment for your script, use pipx for command-line tools, or install the distribution package (for example python3-requests). Avoid --break-system-packages on servers.
59. Two cron runs overlapped and corrupted a state file. How do you stop it?
Use an exclusive, non-blocking lock so the second run exits, and write the state file atomically (question 33).
import fcntl # Linux and macOS only
import sys
with open("/tmp/nightly-sync.lock", "w") as lock_file:
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
sys.exit("another run is still in progress, exiting")
# ... do the sync; the lock is released when the file closes
fcntl exists only on Unix-like systems. On a systemd host, a timer unit does not start a new run while the previous service is still active, which avoids overlap without code.
60. A Lambda function fails with NoSuchKey for files whose names contain spaces. Why?
S3 event notifications URL-encode object keys, so my report.csv arrives as my+report.csv. Decode the key with urllib.parse.unquote_plus() before calling get_object, as in question 32.
61. A deployment script failed, but the pipeline stayed green. How?
The script caught the exception, logged it and then returned normally, so the exit code was 0. Another cause is a shell step such as python deploy.py | tee out.log without set -o pipefail, where the pipeline reports the exit code of tee. Let failures propagate or call sys.exit(1), and enable pipefail in shell steps. Our guide on handling errors in shell scripts covers the shell side.
How to prepare for a Python DevOps interview
- Write three small tools end to end: a log analyser, a boto3 inventory or cleanup script with dry-run, and an HTTP health checker that sets the exit code.
- Add tests for each with pytest, moto and monkeypatch, and run them in a CI pipeline.
- Package one of them with
pyproject.tomland install it with pipx. - Practise explaining each design choice: why a timeout, why pagination, why dry-run.
For more script ideas, see Python scripts for DevOps automation and DevOps task automations using Python. For language-level topics such as decorators, generators and the data model, read our advanced Python interview questions.
DevOps Training Institute runs DevOps training with classroom batches in Kharadi, Pune and live online classes across India, and Python automation is part of the hands-on work. If your target roles are AWS-heavy, the AWS Certified DevOps Engineer Professional course pairs well with the boto3 questions above.
FAQs
How much Python does a DevOps engineer need to know?
Enough to write and maintain automation scripts: files and paths, JSON and YAML, subprocess, HTTP calls, a cloud SDK such as boto3, logging, error handling, virtual environments and pytest. Advanced language features matter less than writing scripts that fail safely and can be tested.
Should I learn Bash or Python first for DevOps?
Learn enough Bash to work on Linux servers and read existing scripts, then learn Python for anything that parses data, calls APIs or needs tests. Most DevOps roles expect both. Use Bash for short command chains and Python once a script grows beyond that.
Which Python version should I use for DevOps scripts in 2027?
Use a version that is still receiving security fixes and that your platforms support, such as Python 3.12 or later. Check the end-of-support dates on python.org and the runtimes your targets offer, for example the AWS Lambda Python runtimes, before choosing.
Which Python libraries should a DevOps engineer know?
From the standard library: subprocess, pathlib, json, logging, argparse, concurrent.futures and shutil. Third-party: boto3 for AWS, requests for HTTP, PyYAML for YAML, pytest and moto for testing, plus the Kubernetes Python client or Jinja2 if your work involves them.
Do DevOps interviews include a live Python coding round?
Many include a short practical task instead of algorithm puzzles: parse a log file, call an API and summarise the result, or write a cleanup script. Interviewers watch for timeouts, error handling, exit codes and whether you test before acting.
How do I practise scenario-based Python questions without an AWS bill?
Run the boto3 examples against moto, which fakes AWS services in memory, and use pytest's monkeypatch to fake subprocess calls. When you need real AWS, use a free tier account with budgets and alerts set, and always start with dry-run flags.
Is Python enough to get a DevOps job?
No. Python is one skill among several. DevOps roles also expect Linux, Git, CI/CD, containers, Kubernetes, infrastructure as code and at least one cloud platform. Python makes the automation parts of those jobs easier.
Official references
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0