Scenario Questions
Real-world Python for DevOps situations and how to reason through them in an interview
Automation scripting & CLI design
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 Your team has a 300-line Bash script that parses JSON with jq, loops over AWS accounts and retries with sleep. It breaks every month. Do you rewrite it in Python?
Beginner
jq, loops over AWS accounts and retries with sleep. It breaks every month. Do you rewrite it in Python?Situation read โ The script has outgrown Bash: data structures, API calls, retries and error handling are all things Bash does badly.
What I'd do โ
- Write down what it actually does today (inputs, outputs, side effects, exit codes) and capture a sample run's output as a reference.
- Rewrite in Python with boto3, a click CLI, logging and built-in retries (
Config(retries={"mode": "adaptive"})), keeping the same flags and output so callers do not change. - Add pytest tests with moto for the core logic and compare output against the reference run.
- Ship it side by side for one cycle, then switch callers over.
Why โ A behaviour-preserving rewrite with tests removes the monthly breakage without surprising the people who depend on it.
Interview tip โ Say you keep the external contract identical; rewrites fail when they change behaviour and tooling at the same time.
Q2 A colleague's script deletes files older than 30 days from /var/log/app. You are asked to review it before it goes into cron. What do you look for?
Intermediate
/var/log/app. You are asked to review it before it goes into cron. What do you look for?Situation read โ Destructive script, unattended execution. Review for blast radius and safety.
What I'd do โ
- Check the path is a constant or validated, never empty: a bug that turns the base into
/or""must abort. - Check it uses
Path.rglobwith explicit patterns (*.log*) and skips symlinks (p.is_symlink()), so it cannot follow a link out of the directory. - Confirm age uses
st_mtimeagainst timezone-consistenttime.time(). - Require a
--dry-rundefault or flag, log every deletion, and exit non-zero on errors. - Catch
PermissionErrorper file and continue, instead of aborting halfway. - Ask whether
logrotatealready does this, which is usually the better answer.
Why โ Cleanup scripts fail dangerously at their edges: empty variables, symlinks and permissions.
Interview tip โ Mention logrotate or find -mtime +30 -delete; not every problem needs Python.
Q3 You need a script that ops engineers run from laptops and that CI runs nightly. How do you design its interface?
Intermediate
Situation read โ Two audiences: humans (readable output, prompts) and machines (stable output, exit codes, no prompts).
What I'd do โ
- click CLI with subcommands, every option settable via env var (
envvar=). --format table|json; default to table whensys.stdout.isatty()and JSON otherwise.- Logs on stderr, data on stdout;
-v/-vvfor verbosity. - Documented exit codes: 0 clean, 1 error, 2 findings.
- No interactive prompt when stdin is not a TTY; destructive actions require
--yes. - Package it with a console script so both laptop (
pipx install) and CI (docker run) use the same entry point.
Why โ One tool, two consumers, no forked logic.
Interview tip โ "stdout is an API" is the phrase interviewers like to hear.
Q4 A script reads a 15 GB access log to count 5xx errors per endpoint, and the box runs out of memory. How do you fix it?
Beginner
Situation read โ It almost certainly does f.read() or readlines(), loading the whole file.
What I'd do โ
- Iterate the file object line by line (
for line in f) and update aCounter. - Use
gzip.open(path, "rt")for compressed rotations instead of decompressing to disk. - Precompile the regex, or use
line.split()if the format is fixed. - Open with
errors="replace"so a single bad byte does not kill the run.
codes = Counter()
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
parts = line.split()
if len(parts) > 8 and parts[8].startswith("5"):
codes[parts[6]] += 1Why โ Streaming keeps memory constant regardless of file size.
Interview tip โ Mention that for recurring analysis the right fix is to ship logs to a system built for it (Loki, CloudWatch Logs Insights, Athena).
Q5 You must run the same Python automation on 40 servers that have Python 3.6, 3.9 and 3.12. What do you do?
Intermediate
Situation read โ Python 3.6 is long end-of-life, and the modern boto3/requests versions no longer support it.
What I'd do โ
- Do not depend on the system Python at all. Options: run the tool in a container, ship a self-contained venv built with the right version (
uv python install 3.12+ venv), or use a single-file zipapp built withshiv/pextargeting a known interpreter. - If agentless remote execution is the real need, use Ansible or SSM Run Command and keep the Python on the control side.
- Open a ticket to upgrade the 3.6 hosts; they are also missing security fixes.
Why โ Writing to the lowest common denominator freezes you on dead versions and unsupported libraries.
Interview tip โ Say "the OS Python belongs to the OS"; ship your own runtime.
Q6 A cron job that runs a Python script fails silently. Nobody noticed for two weeks. How do you make sure that never happens again?
Intermediate
Situation read โ Two problems: the failure itself and the lack of observability.
What I'd do โ
- Make the script exit non-zero on any failure (no catch-all
except: pass). - In crontab, call the venv interpreter explicitly and capture output:
0 2 * * * /opt/tool/.venv/bin/python -m tool >> /var/log/tool.log 2>&1. - Add a dead man's switch: on success, ping Healthchecks.io/Cronitor or push
last_success_timestamp_secondsto a Pushgateway, and alert when it is stale. - Better: move it to a systemd timer (journal logs,
OnFailure=unit) or a Kubernetes CronJob with alerting on failed jobs.
Why โ Alerting on absence of success catches every failure mode, including "never started".
Interview tip โ "Alert on missing success, not just on errors" shows real on-call experience.
Q7 Product wants a Slack notification whenever a deploy finishes. You have 30 minutes. What do you build?
Beginner
Situation read โ Small, well-scoped integration; the risk is leaking the webhook URL or blocking the deploy on Slack.
What I'd do โ
- Create a Slack incoming webhook; store the URL as a CI secret.
- Add a tiny script or step:
import os, requests
resp = requests.post(os.environ["SLACK_WEBHOOK_URL"],
json={"text": f":rocket: {os.environ['SERVICE']} {os.environ['VERSION']} deployed to prod"},
timeout=5)
resp.raise_for_status()- Run it with
if: always()and report success or failure; make the notify step non-blocking (continue-on-error: true).
Why โ A notification must never fail a successful deploy.
Interview tip โ Mention keeping the webhook URL secret; it is a credential.
Q8 You inherit a script with hardcoded AWS keys, a hardcoded account ID and a hardcoded region. What is your clean-up plan?
Beginner
Situation read โ A credential leak (the keys are in Git history) and an inflexible design.
What I'd do โ
- Treat the keys as compromised: deactivate and delete them in IAM now, check CloudTrail for misuse.
- Remove them from code; rely on the default credential chain (profile, SSO, instance role, OIDC in CI).
- Make region and account inputs:
--region,--profile, or derive the account withsts.get_caller_identity(). - Purge history if the repo is shared (
git filter-repo), and addgitleaks/push protection to prevent recurrence.
Why โ Removing keys from the latest commit does not remove them from history or from anyone's clone.
Interview tip โ Lead with "rotate first, then clean the code"; order matters.
Q9 A teammate keeps adding flags to a single script until it has 34 options. How do you restructure it?
Intermediate
Situation read โ One script is doing several jobs; options interact in confusing ways.
What I'd do โ
- Group functionality into subcommands (
tool snapshots cleanup,tool ec2 audit) with a click group. - Move shared options (profile, region, verbosity, format) to the group level and pass them via
ctx.obj. - Put rarely changed settings in a config file with env-var overrides.
- Split the code into modules per subcommand, with a thin CLI layer.
Why โ Subcommands make the help text navigable and isolate options that only make sense together.
Interview tip โ Mention that kubectl and aws are the model: verb/noun subcommands with global flags.
Q10 Your script must process 50,000 S3 keys and must be resumable if it crashes midway. How do you design it?
Advanced
Situation read โ Long-running batch, partial failure is likely, reprocessing must be safe.
What I'd do โ
- Make per-item work idempotent (re-copying or re-tagging the same object is harmless).
- Record progress durably: a checkpoint file written atomically every N items with the last processed key (S3 lists keys in lexicographic order, so
StartAfter=last_keyresumes the listing), or a DynamoDB/SQLite table of done keys. - Handle SIGTERM: finish the current item, write the checkpoint, exit.
- Collect failures in a separate file for retry instead of aborting the run.
- For bigger jobs, use S3 Batch Operations or fan out via SQS workers.
Why โ Checkpoint plus idempotency means a crash costs minutes, not a full rerun.
Interview tip โ Mention StartAfter; it shows you know how S3 listing works.
Q11 Someone asks you to "just add shell=True" because a pipe in subprocess.run does not work. What do you do?
Intermediate
shell=True" because a pipe in subprocess.run does not work. What do you do?Situation read โ The command includes user-controlled input; shell=True would open command injection.
What I'd do โ
- Do the pipe in Python: run the first command, process
stdoutin Python (often replacinggrep/awkentirely). - If both commands must stay, chain two
Popenobjects withstdout=PIPEandstdin=p1.stdout. - If shell features are truly required with a constant command, use
shell=Trueonly with values passed throughshlex.quote().
p1 = subprocess.Popen(["journalctl", "-u", unit, "--since", "1h ago"], stdout=subprocess.PIPE)
p2 = subprocess.run(["grep", "-c", "ERROR"], stdin=p1.stdout, capture_output=True, text=True)
p1.stdout.close(); p1.wait()Why โ Avoiding the shell eliminates the injection class instead of trying to sanitize it.
Interview tip โ Say "list arguments, no shell" as the default rule.
Q12 You need to update a value in 200 YAML files across a repo (bump an image tag) without destroying comments and formatting. How?
Intermediate
Situation read โ PyYAML safe_load/safe_dump would drop comments, reorder keys and change quoting, making a huge noisy diff.
What I'd do โ
- Use
ruamel.yamlin round-trip mode, which preserves comments, ordering and most formatting. - Iterate files with
Path.rglob("*.yaml"), useload_allfor multi-doc manifests, change only matching keys, and write back only if something changed. - Run it on a branch, review
git diff --stat, and let CI validate (kubeconform,helm lint). - If the files are Kustomize overlays,
kustomize edit set imagemay be simpler.
Why โ Minimal diffs are reviewable diffs.
Interview tip โ Naming ruamel.yaml for round-trip editing is a strong signal.
Q13 A script works on your Mac but fails in the Linux CI runner with odd path and encoding errors. What do you check?
Intermediate
Situation read โ Classic environment drift: case sensitivity, encodings, tool versions.
What I'd do โ
- Case sensitivity: macOS's filesystem is case-insensitive by default;
import Configvsconfig.pyworks on Mac and fails on Linux. - Encoding: always pass
encoding="utf-8"; CI containers may have no locale set. - Hardcoded paths (
/Users/...,~): usePath.home()or config. - Different Python and dependency versions: pin with a lock file and the same Python version (or run tests in the same container image locally).
- BSD vs GNU tools in
subprocesscalls (sed -idiffers).
Why โ Most "works on my machine" bugs are one of these five.
Interview tip โ Suggest running tests in the same Docker image locally and in CI.
Q14 You need to rotate a credential stored in 12 places (Secrets Manager, two Kubernetes secrets, a Jenkins credential and a config file). How would you automate it?
Advanced
Situation read โ Multi-system change; a half-finished rotation is an outage.
What I'd do โ
- Reduce the 12 places to 1: Secrets Manager as source of truth, with External Secrets Operator syncing into Kubernetes and Jenkins reading from it.
- Script the rotation as phases: create new credential (both valid), update the source of truth, wait for consumers to pick it up (verify via health checks), revoke the old one.
- Make each step idempotent and log state so a rerun continues from where it stopped.
- Prefer Secrets Manager's built-in rotation Lambda for supported databases.
Why โ The dual-validity window is what makes rotation zero-downtime.
Interview tip โ Say you would fix the sprawl first; automating 12 copies is automating the problem.
Q15 Your manager asks for a weekly CSV of every EC2 instance, its owner tag and monthly cost across 8 accounts. How do you build it?
Intermediate
Situation read โ Multi-account inventory plus cost data. EC2 APIs do not return cost.
What I'd do โ
- Assume a read-only role in each account (
sts.assume_role) from a central tooling account. - List instances per region with paginators, building rows with
InstanceId, type, state,Ownertag (or"MISSING"). - Get cost from Cost Explorer (
ce.get_cost_and_usagegrouped by a cost allocation tag or resource-level data) or from the CUR in Athena; do not estimate from price lists if real data exists. - Write with
csv.DictWriter, upload to S3, email or post the link. - Schedule weekly in CI with OIDC.
Why โ Inventory from APIs plus cost from billing data is accurate and auditable.
Interview tip โ Mention activating the Owner cost allocation tag; without that, cost by owner is impossible.
Q16 Your Python tool takes 9 seconds just to print --help. Users complain. What do you do?
Advanced
--help. Users complain. What do you do?Situation read โ Heavy top-level imports or work at import time (clients created, network calls).
What I'd do โ
- Measure:
python -X importtime -m tool --help 2>&1 | sort -t'|' -k2 -n | tail -20. - Move expensive imports (boto3, kubernetes, pandas) inside the subcommand functions that use them.
- Remove any import-time side effects: no clients, config loading or API calls at module level.
- Check the venv is not on a slow network filesystem.
Why โ --help should cost only argument parsing; lazy imports make every command start fast.
Interview tip โ -X importtime is the tool to name.
Q17 You must call an internal API that sometimes returns 503 for a few seconds during deploys. Your script fails randomly. Fix it.
Beginner
Situation read โ Transient errors; the client should retry with backoff, not fail.
What I'd do โ
- Use a
requests.Sessionwith anHTTPAdapter(max_retries=Retry(total=5, backoff_factor=1, status_forcelist=(502, 503, 504), respect_retry_after_header=True)). - Keep explicit timeouts (
timeout=(3, 10)). - Only retry idempotent methods automatically.
- Log each retry at WARNING so persistent problems are visible.
Why โ A few seconds of backoff absorbs deploy blips without masking real outages, because retries are bounded.
Interview tip โ Also suggest the API team fix it with readiness probes and connection draining.
Q18 You need to template 50 config files from a list of services. Python string formatting is getting messy. What do you use?
Intermediate
Situation read โ Classic templating problem.
What I'd do โ
- Use Jinja2 (the same engine as Ansible and many Helm-like tools): templates with loops and conditionals, data from YAML.
- Enable
undefined=StrictUndefinedso a missing variable is an error, not an empty string. - Validate output (parse generated YAML/JSON, run
nginx -t) before writing. - Write only changed files, so diffs and reloads are minimal.
env = jinja2.Environment(loader=jinja2.FileSystemLoader("templates"), undefined=jinja2.StrictUndefined)
out = env.get_template("nginx.conf.j2").render(svc=svc)Why โ Templates separate structure from data and fail loudly on missing values.
Interview tip โ Mention StrictUndefined; silent empty values are the classic template bug.
Q19 A script runs for 6 hours and you want to know where the time goes without restarting it. How?
Advanced
Situation read โ Need live introspection of a running process.
What I'd do โ
py-spy top --pid <pid>to see which functions are consuming time right now.py-spy dump --pid <pid>to see each thread's current stack; repeated dumps show if it is stuck on the same call (a network call with no timeout is the usual culprit).py-spy record -o profile.svg --pid <pid> --duration 60for a flame graph.- Next run: add timing logs per phase and a progress counter.
Why โ py-spy samples from outside the process with no code changes or restart.
Interview tip โ "Six hours" is often a missing timeout or sequential API calls; mention both.
Q20 You are asked to write a "self-healing" script that restarts a service when its health check fails. What design concerns do you raise?
Intermediate
Situation read โ Auto-remediation can hide problems or cause restart storms.
What I'd do โ
- Prefer platform features first: systemd
Restart=on-failurewithStartLimitBurst, Kubernetes liveness probes, ASG health checks. - If a script is still needed: require N consecutive failures before acting, add a cooldown, cap restarts per hour, and alert a human after the cap.
- Log and emit a metric for every remediation so frequency is visible.
- Never remediate on a dependency failure (restarting the app does not fix the DB).
Why โ Unbounded auto-restart turns a degraded service into a flapping one.
Interview tip โ Say every auto-remediation must also notify; silent healing hides the root cause.
Q21 A security review flags that your tool uses pickle to cache API responses on disk. What do you change?
Intermediate
pickle to cache API responses on disk. What do you change?Situation read โ pickle.load on a file someone else can write is arbitrary code execution.
What I'd do โ
- Switch the cache to JSON (or
sqlite3), which is data-only. - Store it in a user-owned directory with
0600permissions (platformdirs.user_cache_dir). - Add expiry metadata so stale data is not trusted forever.
Why โ JSON cannot execute code on load; pickle can.
Interview tip โ Know the rule: never unpickle data you did not produce in a location only you can write.
Q22 You need to compare the live state of 300 Route 53 records against a desired YAML file and report drift. How do you approach it?
Advanced
Situation read โ Desired vs actual reconciliation, report-only.
What I'd do โ
- Load desired records from YAML into a dict keyed by
(name, type), normalizing names (trailing dot, lowercase) and sorting values. - Fetch actual with the
list_resource_record_setspaginator, normalized the same way. - Compute set differences: missing, extra, changed (compare TTL and sorted values).
- Output a diff report (Markdown + JSON) and exit 2 if drift exists.
- Recommend moving the zone into Terraform so drift detection is
terraform plan.
Why โ Normalization is the hard part; without it every record looks drifted.
Interview tip โ Mention normalization explicitly; it is what separates a working diff from noise.
Q23 Your CLI needs to show progress for a 20-minute operation, but it also runs in CI. What do you do?
Beginner
Situation read โ Progress bars are great in terminals and garbage in CI logs.
What I'd do โ
- Use
tqdmorrich.progressonly whensys.stderr.isatty(); otherwise log a line every N items or every 30 seconds. - Write progress to stderr, never stdout.
- Respect
NO_COLORand a--quietflag.
Why โ Carriage-return progress bars produce thousands of log lines in CI.
Interview tip โ TTY detection is the one-line answer.
Q24 A new joiner asks why your team's scripts all use logging.getLogger(__name__) instead of the root logger. How do you explain it?
Beginner
logging.getLogger(__name__) instead of the root logger. How do you explain it?Situation read โ Teaching moment about logger hierarchy.
What I'd do โ
- Explain that named loggers show which module emitted a line (
cloudaudit.checks). - Levels can be tuned per module:
logging.getLogger("cloudaudit.checks").setLevel("DEBUG")without drowning in botocore debug logs. - Libraries should never configure the root logger; the application does it once in
main().
Why โ Named loggers give control and context for free.
Interview tip โ Mention silencing botocore and urllib3 to WARNING as a practical example.
Q25 You need to run a one-off data fix against production through a Python script. How do you make it safe?
Advanced
Situation read โ One-off scripts skip review and testing, and touch production directly.
What I'd do โ
- Code review the script like any change; check it into the repo under
oneoff/with a ticket reference. - Dry-run mode that prints exactly what will change, with counts, and a hard cap (
--max-items). - Back up or snapshot affected data first.
- Run in a controlled environment (bastion or CI job with an audited role), with output captured.
- Pair with a second engineer during the run; verify after.
Why โ One-off scripts cause a disproportionate share of incidents because they bypass normal controls.
Interview tip โ "Peer review plus dry-run plus backup plus cap" is the four-part answer.
AWS automation with boto3
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q26 You are asked to write a script that stops all dev EC2 instances at 8 PM and starts them at 8 AM. How do you build it?
Beginner
Situation read โ Classic cost-saving automation; the risk is stopping the wrong instances.
What I'd do โ
- Select only instances tagged
Environment=devandSchedule=office-hours(opt-in, never "everything not prod"). - Use a paginator with
Filtersfor the tags and the current state. - Call
stop_instances/start_instancesin batches, log IDs, support--dry-run(andDryRun=Trueto verify permissions). - Run it as a Lambda on EventBridge Scheduler (cron with time zone), with a role allowed only
ec2:StopInstances/StartInstanceson resources with that tag (IAM conditionaws:ResourceTag/Schedule).
Why โ Opt-in tags plus IAM conditions make it impossible to stop prod even if the code is wrong.
Interview tip โ Mention the IAM tag condition; it is defence in depth beyond the code filter.
Q27 A script that lists all S3 objects in a bucket reports 1,000 objects, but the console says there are 48,000. What happened, and how do you fix the script?
Beginner
Situation read โ list_objects_v2 returns at most 1,000 keys per call; the script read one page.
What I'd do โ
- Replace the single call with a paginator:
total = 0
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
total += page.get("KeyCount", 0)- Audit other scripts for the same bug on any
list_*/describe_*call. - For counts and sizes across huge buckets, use S3 Inventory or Storage Lens instead of listing.
Why โ Every AWS list API is paginated; one page is not the answer.
Interview tip โ Say "pagination bugs are silent: no error, just wrong data".
Q28 You need to find and delete EBS snapshots older than 90 days, but some are used by AMIs and backup plans. How do you write it safely?
Intermediate
Situation read โ Old snapshot cleanup with dependencies; deleting the wrong one breaks AMIs or compliance retention.
What I'd do โ
- List with
describe_snapshots(OwnerIds=["self"])paginator; filterStartTime < now - 90dusing timezone-aware datetimes. - Exclude snapshots referenced by registered AMIs (
describe_images(Owners=["self"]), collectBlockDeviceMappings[].Ebs.SnapshotId). - Exclude snapshots managed by AWS Backup or DLM (tags like
aws:backup:source-resourceordlm:managed) and anything taggedRetain=true. - Dry-run report first; delete with
delete_snapshot, handlingInvalidSnapshot.InUseas skip, not failure. - Long term, let DLM or AWS Backup own retention.
Why โ Delete only what you can prove is unowned.
Interview tip โ Mentioning the AMI cross-check shows you have actually done this.
Q29 Your audit script hits ThrottlingException / RequestLimitExceeded when scanning large accounts. What do you change?
Advanced
ThrottlingException / RequestLimitExceeded when scanning large accounts. What do you change?Situation read โ Too many calls too fast, probably from parallelism or per-resource describe calls.
What I'd do โ
- Configure
Config(retries={"mode": "adaptive", "max_attempts": 10})so botocore backs off and rate-limits client-side. - Reduce call volume: filter server-side, batch IDs into one describe call, use
get_metric_datainstead of per-instanceget_metric_statistics. - Lower
max_workersor add a per-service semaphore. - Consider AWS Config advanced queries or Resource Explorer for inventory.
Why โ Fewer calls beats faster retries.
Interview tip โ Say you would check whether another tool in the same account is consuming the same quota.
Q30 You must audit 40 AWS accounts in an Organization from one script. How do you handle credentials?
Advanced
Situation read โ Cross-account access, centrally.
What I'd do โ
- Deploy an
AuditReadOnlyrole to every account via StackSets or Terraform, trusting only a role in the security/tooling account. - List accounts with
organizations.list_accounts(paginator) from the management or delegated admin account. - For each account,
sts.assume_roleinto the audit role and build a fresh Session from the returned credentials. - Run accounts in parallel with a bounded pool; catch
AccessDeniedper account and report rather than abort.
Why โ One trust path, least privilege, no keys in any account.
Interview tip โ Mention ExternalId only matters for third-party access; inside an org, condition on aws:PrincipalOrgID.
Q31 A Lambda written in Python times out at 15 minutes while processing a big S3 prefix. What are your options?
Advanced
Situation read โ Lambda's hard maximum is 15 minutes; the job is too big for a single invocation.
What I'd do โ
- Fan out: one Lambda lists keys and sends batches to SQS; worker Lambdas process batches concurrently.
- Or use Step Functions Distributed Map over the S3 prefix.
- Or move to a container job on ECS/Fargate or AWS Batch with no time limit.
- Optimize per item: reuse clients created outside the handler, parallelize I/O with threads.
Why โ Lambda is designed for short, parallel work; long sequential jobs belong elsewhere.
Interview tip โ Mention creating boto3 clients outside the handler so warm invocations reuse connections.
Q32 You are asked to tag every untagged resource in an account with Owner=unknown. What questions do you ask and how do you implement it?
Intermediate
Owner=unknown. What questions do you ask and how do you implement it?Situation read โ Bulk change across services; "untagged" and "every" need definitions.
What I'd do โ
- Ask: which tag keys are required, which resource types, and is
unknowna real value or should we find the creator? - Find resources with the Resource Groups Tagging API (
get_resourcespaginator) and filter those missing the key. Note it only returns resources that have, or once had, tags; fully untagged resources may need per-service describes or AWS Config. - Look up creators via CloudTrail (
lookup_eventsforRunInstances) to set a real owner where possible. - Apply with
tag_resourcesin batches of 20 ARNs, dry-run first. - Prevent recurrence with tag policies and SCPs requiring tags on create.
Why โ Backfilling once is pointless without enforcement going forward.
Interview tip โ Say "find the creator in CloudTrail" before defaulting to unknown.
Q33 A script must create an S3 bucket if it does not exist, and it runs in parallel CI jobs. How do you make it race-safe?
Advanced
Situation read โ Check-then-create races between jobs.
What I'd do โ
- Skip the check; call
create_bucketand treatBucketAlreadyOwnedByYouas success. - Treat
BucketAlreadyExists(someone else owns the name globally) as a real error. - Pass
CreateBucketConfiguration={"LocationConstraint": region}outsideus-east-1. - Apply settings (encryption, public access block, versioning) idempotently after creation.
- Better: create buckets once in Terraform, not in CI jobs.
Why โ EAFP avoids the time-of-check/time-of-use race.
Interview tip โ Know the two error codes and what each means.
Q34 You need to find every security group that allows 0.0.0.0/0 on any port other than 80 and 443. How do you write the check?
Intermediate
Situation read โ Port ranges and protocol -1 are the edge cases.
What I'd do โ
- Paginate
describe_security_groups. - For each
IpPermissionsentry, checkIpRanges[].CidrIp == "0.0.0.0/0"andIpv6Ranges[].CidrIpv6 == "::/0". - Handle
IpProtocol == "-1"(all traffic, no port fields), and ranges (FromPorttoToPort) that include more than 80/443. - Check whether the SG is attached (
describe_network_interfaceswithgroup-idfilter) to prioritize.
allowed = {80, 443}
risky = proto == "-1" or not (lo == hi and lo in allowed)Why โ Rules like 0-65535 or protocol -1 are the most dangerous and the most commonly missed.
Interview tip โ Mention IPv6; many audits forget ::/0.
Q35 Finance asks why EC2 spend doubled last month. You have Python and read access. What do you do?
Intermediate
Situation read โ Cost investigation; the data is in Cost Explorer, not EC2.
What I'd do โ
- Query Cost Explorer:
ce.get_cost_and_usage(TimePeriod=..., Granularity="DAILY", Metrics=["UnblendedCost"], GroupBy=[{"Type": "DIMENSION", "Key": "USAGE_TYPE"}])to see when and which usage type jumped. - Group by
LINKED_ACCOUNT,REGION,INSTANCE_TYPEand by theOwnertag to narrow it. - Cross-check with CloudTrail
RunInstancesevents around the day of the jump. - Report with a daily chart and the specific resources.
Why โ Start from billing data and drill down; do not guess from current inventory.
Interview tip โ Note that Cost Explorer API calls cost $0.01 each, so cache results.
Q36 You need to wait until a newly created RDS instance is available before running migrations. How?
Intermediate
Situation read โ Use a waiter instead of a sleep loop.
What I'd do โ
rds.get_waiter("db_instance_available").wait(DBInstanceIdentifier=name, WaiterConfig={"Delay": 30, "MaxAttempts": 60}).- Catch
botocore.exceptions.WaiterErrorand report the last status. - Then fetch the endpoint from
describe_db_instancesand check TCP connectivity before migrating.
Why โ Waiters handle polling, intervals and failure states consistently.
Interview tip โ Mention that "available" in the API does not guarantee your network path works; check connectivity too.
Q37 Your script uses boto3.resource("ec2") and a new team member asks whether to keep using resources. What do you advise?
Beginner
boto3.resource("ec2") and a new team member asks whether to keep using resources. What do you advise?Situation read โ AWS has feature-frozen the resource interface.
What I'd do โ
- Keep existing working code, but write new code with clients.
- Clients cover every API and new features; resources will not get new services or operations.
- Clients return plain dicts, which are easy to test with moto or Stubber and to type with boto3-stubs.
Why โ Long-term maintainability and full API coverage.
Interview tip โ Know that the resource interface is frozen; it often comes up.
Q38 You need to copy an AMI to three regions and share it with two accounts as part of a release. How do you automate it?
Advanced
Situation read โ Multi-region, multi-account, slow async operations.
What I'd do โ
- For each region, call
copy_image(SourceRegionId=..., SourceImageId=..., Name=..., Encrypted=True, KmsKeyId=regional_key)from a client in the destination region. - Wait with
get_waiter("image_available")in each region (in parallel threads). - Share:
modify_image_attribute(ImageId=..., LaunchPermission={"Add": [{"UserId": acct}]}), and grant the accounts use of the KMS key (or the snapshots will be unusable). - Tag copies with source AMI and version; publish IDs to SSM parameters per region.
- Use EC2 Image Builder distribution settings if available.
Why โ Encrypted AMI sharing fails silently without KMS grants; that is the usual gotcha.
Interview tip โ Mention KMS key permissions for shared encrypted snapshots.
Q39 A boto3 script works locally with your SSO profile but fails in CI with NoCredentialsError. What is the plan?
Intermediate
NoCredentialsError. What is the plan?Situation read โ CI has no profile and no credentials configured.
What I'd do โ
- Set up GitHub OIDC: an IAM OIDC provider for
token.actions.githubusercontent.comand a role trusting your repo and branch. - Add
permissions: id-token: writeandaws-actions/configure-aws-credentials@v4withrole-to-assumeandaws-region. - Remove any
profile_name="..."hardcoding from the script; let the default chain pick up env credentials.
Why โ OIDC gives short-lived credentials with no secrets to store or rotate.
Interview tip โ Mention restricting the trust policy sub claim to repo:org/name:ref:refs/heads/main.
Q40 You need to process every new file uploaded to an S3 bucket with Python. Design it.
Intermediate
Situation read โ Event-driven processing; must handle bursts and failures.
What I'd do โ
- S3 event notification to SQS (or EventBridge), with a Lambda or container worker consuming from SQS.
- Worker parses the event, URL-decodes the key (
urllib.parse.unquote_plus, keys arrive encoded), processes, and deletes the message only on success. - Configure a dead-letter queue and alarm on its depth.
- Make processing idempotent (S3 can deliver events more than once), keyed on bucket, key and version or ETag.
Why โ A queue buffers bursts and gives retries plus a DLQ for free.
Interview tip โ The unquote_plus detail catches many people; keys with spaces arrive as +.
Q41 How would you write a Python script that enforces "no public S3 buckets" across accounts?
Intermediate
Situation read โ Detection and remediation; prevention is better.
What I'd do โ
- Prevent first: account-level S3 Block Public Access (
s3control.put_public_access_block) and an SCP that denies changing it. - Detect: for each bucket, check
get_public_access_block, bucket policy status (get_bucket_policy_statusreturnsIsPublic), and ACLs; handleNoSuchPublicAccessBlockConfigurationas "not set". - Remediate with an allow-list for intentional public buckets (static sites behind CloudFront should use OAC instead).
- Report findings; auto-remediate only with approval.
Why โ Account-level controls stop the problem; scripts verify they stay on.
Interview tip โ Mention get_bucket_policy_status; it saves you parsing policies yourself.
Q42 A script that runs describe_instances with 2,000 instance IDs fails with a filter limit error. How do you fix it?
Intermediate
describe_instances with 2,000 instance IDs fails with a filter limit error. How do you fix it?Situation read โ EC2 limits the number of values in a filter or ID list per request.
What I'd do โ
- Chunk the IDs into batches (for example 200) and call per batch, or use a paginator with no ID list and filter in Python.
- Write a generic
chunked()helper and reuse it for other batch-limited APIs (tag_resourcesmax 20 ARNs,delete_objectsmax 1,000 keys).
for batch in chunked(ids, 200):
for page in ec2.get_paginator("describe_instances").paginate(InstanceIds=batch): ...Why โ Every batch API has a documented limit; chunking is the standard pattern.
Interview tip โ Quote a couple of real limits; it shows hands-on experience.
Q43 You need to rotate IAM access keys older than 90 days for service users and notify owners. What do you build?
Advanced
Situation read โ Keys should not exist at all for most services; the script is a stopgap.
What I'd do โ
- Get the credential report (
iam.generate_credential_report, poll, thenget_credential_report, parse CSV) for key age and last used. - Flag keys older than 90 days; for unused keys (no
last_used_datein 90 days) deactivate, then delete after a grace period. - Notify owners via the
Ownertag on the user, with a deadline. - Track the real fix: move each workload to roles (OIDC, instance profiles, IRSA) and delete the user.
Why โ The credential report gives everything in one call instead of N list_access_keys calls.
Interview tip โ Say the goal is zero long-lived keys; rotation is risk reduction, not the solution.
Q44 You are writing a cleanup Lambda that deletes unattached EBS volumes. How do you avoid deleting something important?
Intermediate
Situation read โ "Unattached" (State=available) does not mean "unwanted".
What I'd do โ
- Filter
status=available, then require a minimum age since detachment (CloudTrailDetachVolumetime or adetached-attag set by a first pass). - Skip volumes tagged
Retain=trueor owned by a known system. - Snapshot before deletion (tag the snapshot with source volume and date) for a recovery window.
- Run in report mode for two weeks before enabling deletion.
Why โ A two-phase "mark, then sweep" design gives owners time to object.
Interview tip โ "Mark and sweep with a grace period" is the pattern name to use.
Q45 You need to know which IAM permissions your Python tool needs. How do you find the minimum?
Advanced
Situation read โ Least privilege for automation roles.
What I'd do โ
- List every boto3 call in the code; map each to its IAM action (usually
service:OperationName, but not always, e.g.list_objects_v2iss3:ListBucket). - Run the test suite or a sandbox run with CloudTrail and use IAM Access Analyzer policy generation from the CloudTrail activity.
- Scope resources and conditions where the API supports it (tag conditions, specific ARNs).
- Document the policy in the README and keep it in Terraform.
Why โ Generated policies from real activity are accurate; guessing leads to *.
Interview tip โ Mention Access Analyzer policy generation by name.
Q46 You want your boto3 code to be testable without moto for pure logic. How do you structure it?
Intermediate
Situation read โ Separate decisions from API calls.
What I'd do โ
- Fetch functions return plain data (lists of dicts).
- Rule functions take that data and return findings or actions, with no boto3 inside.
- Act functions take actions and call APIs.
- Test rules with plain dicts in milliseconds; test fetch/act with moto or Stubber.
Why โ Most bugs are in the rules, and rules are trivial to test once they do not touch the network.
Interview tip โ "Functional core, imperative shell" is the phrase.
Q47 CloudWatch shows no CPUUtilization data for some instances, and your idle-instance check flags them as idle. What is wrong with the check?
Intermediate
CPUUtilization data for some instances, and your idle-instance check flags them as idle. What is wrong with the check?Situation read โ "No data" is being treated as "zero CPU".
What I'd do โ
- Treat empty
Datapointsas unknown and skip (or report separately), never as idle. - Check why there is no data: newly launched, stopped most of the period, wrong region or dimension, or the metric name typo.
- Require a minimum number of datapoints over the window before judging.
- Consider network and disk metrics too; a low-CPU instance can be a busy proxy.
Why โ Missing data is not evidence of idleness; acting on it stops real workloads.
Interview tip โ Our lab's idle_instances check skips instances without datapoints for exactly this reason.
Q48 A colleague wants to use boto3 from inside a Kubernetes pod with access keys mounted as a Secret. What do you suggest?
Beginner
boto3 from inside a Kubernetes pod with access keys mounted as a Secret. What do you suggest?Situation read โ Long-lived keys in a cluster are avoidable.
What I'd do โ
- On EKS, use EKS Pod Identity or IRSA: bind an IAM role to the pod's service account.
- boto3 picks up the credentials automatically (web identity token or container credentials endpoint); no code change.
- Scope the role to the specific actions and resources.
Why โ Short-lived, automatically rotated credentials tied to one workload.
Interview tip โ Mention that a recent boto3 version is needed for Pod Identity support; old images fail with NoCredentialsError.
Q49 You must export all CloudWatch alarms in an account to a YAML file for review. How do you build it?
Beginner
Situation read โ Read-only export.
What I'd do โ
- Paginate
describe_alarms(metric and composite alarms). - Select relevant fields (name, metric, threshold, comparison, actions, state).
- Convert datetimes to ISO strings, then
yaml.safe_dump(data, sort_keys=False). - Commit the YAML to a repo so changes show up as diffs over time.
Why โ A versioned export turns an opaque console setting into reviewable config.
Interview tip โ Suggest managing alarms as code (Terraform) as the next step.
Q50 Your audit tool takes 40 minutes across 17 regions. How do you get it under 5?
Advanced
Situation read โ Sequential I/O across regions and services.
What I'd do โ
- Run regions concurrently with
ThreadPoolExecutor, one boto3 Session per worker thread. - Within a region, run independent checks concurrently too, bounded per service.
- Replace per-resource calls with batch calls (
get_metric_data, filters). - Skip regions that are disabled or have no resources (
describe_regions). - Measure per-phase timings in logs to target the slowest part.
Why โ The work is almost entirely network wait, which threads overlap well.
Interview tip โ Mention Sessions not being thread-safe; it is a common follow-up.
Kubernetes, Docker, SSH & fleet automation
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q51 You need a report of every pod in the cluster with no CPU or memory limits. How do you write it?
Beginner
Situation read โ Read-only audit with the Kubernetes client.
What I'd do โ
config.load_kube_config(), thenCoreV1Api().list_pod_for_all_namespaces(limit=500), paginating with_continue.- For each container (including init containers), check
container.resources.limitsforcpuandmemory;resources.limitscan beNone. - Output namespace, pod, owner (from
metadata.owner_references), container and missing limits as CSV. - Long term: enforce with a LimitRange or an admission policy (Kyverno, Gatekeeper, or ValidatingAdmissionPolicy).
Why โ Reports find existing gaps; admission policies stop new ones.
Interview tip โ Report by owner (Deployment), not pod, so teams can fix the source.
Q52 You are asked to write a small operator-like script that adds a label to every new namespace. How do you approach it?
Advanced
Situation read โ Event-driven reconciliation; watches can drop and expire.
What I'd do โ
- Consider whether a mutating admission policy or Kyverno rule does this declaratively; usually it does.
- If code is needed, use
kopf(handles watches, retries, and resumption) or a watch loop that lists first, reconciles all, then watches from the list'sresourceVersion. - Handle
410 Goneby re-listing, and reconnect on timeouts. - Patch idempotently (only if the label is missing).
- Run in-cluster with a service account allowed only
get, list, watch, patchon namespaces.
Why โ Level-triggered reconciliation (look at all current state) survives missed events.
Interview tip โ Say "level-triggered, not edge-triggered" and mention 410 Gone.
Q53 You need to restart all Deployments in a namespace that reference a rotated Secret. How?
Advanced
Situation read โ Pods do not reload env vars from Secrets automatically.
What I'd do โ
- List Deployments; find ones referencing the secret in
env[].valueFrom.secretKeyRef,envFrom[].secretReforvolumes[].secret. - Patch each with the
kubectl.kubernetes.io/restartedAtannotation on the pod template, triggering a rolling restart. - Watch rollout status (
status.updatedReplicas == spec.replicasandavailableReplicas) before moving to the next. - Long term: use Reloader or a checksum annotation in Helm so this is automatic.
Why โ One-at-a-time rollouts avoid restarting everything simultaneously.
Interview tip โ Mention that volume-mounted Secrets update in place (eventually) but env vars never do.
Q54 Your CI runners keep running out of disk because of Docker images. Write a cleanup plan in Python.
Intermediate
Situation read โ Build caches and old images accumulate on long-lived runners.
What I'd do โ
- Script with the Docker SDK:
containers.prune(),images.prune(filters={"dangling": True}), then remove images older than N days not in an allow-list, andapi.prune_builds()for BuildKit cache. - Run it as a scheduled job and log space reclaimed.
- Alert on disk above 80% (node exporter).
- Better: ephemeral runners that start clean each job.
Why โ Pruning treats the symptom; ephemeral runners remove the cause.
Interview tip โ Mention build cache, which docker image prune does not touch.
Q55 You need to run df -h on 300 Linux hosts and list any above 85%. Python or Ansible?
Beginner
df -h on 300 Linux hosts and list any above 85%. Python or Ansible?Situation read โ Ad-hoc fleet query.
What I'd do โ
- If the fleet is in Ansible inventory:
ansible all -m shell -a "df -hP"or a playbook with a filter; that is the fastest path. - In Python, use Fabric's
ThreadingGroup(*hosts).run("df -P", hide=True, warn=True)and parse output; collect failures separately. - On AWS without SSH: SSM Run Command targeting by tag.
- Long term: node exporter plus an alert, so nobody has to ask.
Why โ The right answer is often "this should be a metric, not a script".
Interview tip โ End with the monitoring answer.
Q56 A Python script SSHes to hosts with AutoAddPolicy. Security says that is unacceptable. What do you change?
Intermediate
AutoAddPolicy. Security says that is unacceptable. What do you change?Situation read โ Blindly trusting host keys allows man-in-the-middle.
What I'd do โ
- Pre-populate known_hosts from a trusted source (keys captured at provisioning time, or SSH certificates signed by your CA).
ssh.load_system_host_keys()orload_host_keys(path)andset_missing_host_key_policy(RejectPolicy()).- Consider SSH certificates (
@cert-authorityin known_hosts) so new hosts are trusted automatically and securely. - On AWS, consider SSM Session Manager to remove SSH entirely.
Why โ Host key verification is what makes SSH resistant to interception.
Interview tip โ SSH certificates are the scalable answer for dynamic fleets.
Q57 You want to validate all Kubernetes manifests in a repo in CI with Python. What would the script check?
Intermediate
Situation read โ Policy checks on YAML before it reaches the cluster.
What I'd do โ
- Parse every file with
yaml.safe_load_all, skipping empty docs; fail on YAML errors with file and line. - Schema-validate with
kubeconform(viasubprocess), not by hand. - Custom rules in Python: image tag not
latest, resources set,runAsNonRoot: true, required labels, nohostPath. - Output findings with file paths; exit non-zero on violations.
- Consider Conftest/Kyverno CLI to share the same policies with the cluster.
Why โ Catching policy violations at PR time is cheaper than at admission time.
Interview tip โ Mention reusing the same policies in CI and in-cluster.
Q58 You need to tail logs from all pods of a Deployment at once in a Python tool. How?
Advanced
Situation read โ Multiple concurrent streams.
What I'd do โ
- List pods by the Deployment's selector (
label_selector="app=api"). - For each pod, stream with
read_namespaced_pod_log(name, ns, container=c, follow=True, _preload_content=False)and iterateresp.stream()in a thread. - Prefix lines with pod name; push lines into a
queue.Queue, print from the main thread. - Watch for new pods (rollouts) and start streams for them.
Why โ One thread per stream is simple and the work is I/O bound.
Interview tip โ Mention stern or kubectl logs -l app=api -f --prefix as existing tools before building one.
Q59 How would you use Python to check that every Docker image running in your cluster comes from your approved registry?
Intermediate
Situation read โ Supply-chain audit.
What I'd do โ
- List all pods; collect
spec.containers[].image,initContainersandephemeralContainers. - Normalize references (no registry means
docker.io/library/); compare against an allowed prefix list (123456789012.dkr.ecr.ap-south-1.amazonaws.com/). - Also check
status.containerStatuses[].imageIDfor the actual digest running. - Enforce with an admission policy (Kyverno
verifyImagesor a registry restriction policy).
Why โ Normalization catches images that look private but are pulled from Docker Hub.
Interview tip โ Mention implicit docker.io and digest vs tag.
Q60 You need to back up a database running in a container every night with Python and upload to S3. Design it.
Advanced
Situation read โ Scheduled backup, streaming to S3, verified.
What I'd do โ
- Run
pg_dump -Fcviasubprocess.Popenand stream stdout straight intos3.upload_fileobj(no local disk needed). - Key by date (
db/2026/11/09/app.dump), SSE-KMS encryption, lifecycle rules for retention. - Check
pg_dump's exit code after the upload; delete the object if the dump failed. - Weekly restore test into a scratch database.
- Run as a Kubernetes CronJob with IRSA/Pod Identity, alert on failure.
Why โ Backups that are never restored are hopes, not backups.
Interview tip โ Restore testing is what interviewers want to hear.
Q61 A Python script needs to run kubectl against three clusters. How do you manage contexts safely?
Intermediate
kubectl against three clusters. How do you manage contexts safely?Situation read โ Risk of running against the wrong cluster.
What I'd do โ
- Never rely on the current context; pass
--contextexplicitly on every call, orconfig.load_kube_config(context=name)with the Python client. - Print the target cluster and require confirmation (or a flag) for prod.
- Use separate kubeconfig files per environment via
KUBECONFIGfor CI jobs.
Why โ "Current context" is shared mutable state; someone else's kubectl config use-context changes your target.
Interview tip โ Mention explicit --context as a habit.
Q62 You need to make 1,000 HTTP health checks every minute against internal endpoints. Threads or asyncio?
Intermediate
Situation read โ High fan-out I/O on a timer.
What I'd do โ
- asyncio with
httpx.AsyncClient(or aiohttp), aSemaphore(100), per-request timeouts (timeout=3), andasyncio.gather(..., return_exceptions=True). - Record results as Prometheus metrics (
probe_success, latency histogram) from a long-running process. - Or just deploy Prometheus
blackbox_exporter, which does exactly this.
Why โ asyncio handles thousands of sockets in one thread cheaply; threads would need a big pool.
Interview tip โ Mentioning blackbox_exporter shows you do not reinvent monitoring.
Q63 You must drain and replace 50 Kubernetes nodes one at a time with Python, respecting PodDisruptionBudgets. How?
Advanced
Situation read โ Controlled rolling node replacement.
What I'd do โ
- For each node: cordon (
patch_node(name, {"spec": {"unschedulable": True}})). - Evict pods with the Eviction API (
create_namespaced_pod_eviction), skipping DaemonSet and mirror pods. A 429 response means a PDB is blocking; back off and retry. - Wait until the node has no evictable pods, then terminate the instance (ASG
terminate_instance_in_auto_scaling_groupwithShouldDecrementDesiredCapacity=False). - Wait for the replacement node to be
Readybefore continuing. - Prefer managed node group updates or Karpenter drift, which do this already.
Why โ The Eviction API respects PDBs; deleting pods directly does not.
Interview tip โ "Evict, don't delete" is the key line.
Q64 Your team wants a ChatOps bot that can scale deployments from Slack. What are your design concerns?
Advanced
Situation read โ Remote control of production from chat.
What I'd do โ
- Verify Slack request signatures (
X-Slack-Signature, HMAC with timestamp check against replay). - Map Slack users to roles; allow-list commands and namespaces; enforce limits (max replicas).
- The bot's Kubernetes service account gets only
patchondeployments/scalein allowed namespaces. - Audit-log every command with user, time and result; post results to the channel.
- Respond within 3 seconds (Slack's limit), process asynchronously.
Why โ ChatOps is an authenticated API to production and needs the same controls.
Interview tip โ Mention signature verification and least-privilege RBAC.
Q65 You need to push a config file to 20 servers and restart a service, but only if the file changed. How in Python?
Intermediate
Situation read โ Idempotent config push; Ansible's template + handler does this.
What I'd do โ
- Compute local SHA-256; on each host run
sha256sumon the remote file via Fabric. - If different:
c.put()to a temp path, validate (nginx -t -c ...),sudo mvinto place,sudo systemctl reload. - Roll through hosts in batches and stop on the first failure.
- Suggest Ansible for anything beyond this.
Why โ Comparing checksums makes the push idempotent and avoids needless restarts.
Interview tip โ Validate before reload; a bad config should never reach the running service.
Q66 A Kubernetes CronJob running a Python script sometimes runs twice at the same time. How do you fix it?
Intermediate
Situation read โ Concurrency policy, or a run that exceeds the schedule interval.
What I'd do โ
- Set
concurrencyPolicy: Forbidon the CronJob. - Set
startingDeadlineSecondsso missed runs do not pile up. - Make the script idempotent anyway; Kubernetes CronJobs can, in rare cases, create two jobs.
- Add an
activeDeadlineSecondsso a hung run is killed.
Why โ Forbid plus idempotency covers both the common and rare double runs.
Interview tip โ Mention that CronJobs are "at least once", not "exactly once".
Q67 You need to check TLS certificate expiry for 400 domains and alert at 21 days. How do you build it?
Intermediate
Situation read โ Simple but valuable check.
What I'd do โ
- For each domain, open a TLS connection with
ssl.create_default_context()andsocket.create_connection((host, 443), timeout=5), wrap withserver_hostname=host, readgetpeercert()["notAfter"], parse withssl.cert_time_to_seconds. - Run concurrently with a thread pool.
- Report domains below 21 days; also report connection or verification failures.
- Or export as metrics and use blackbox_exporter's
probe_ssl_earliest_cert_expiry.
Why โ Expired certificates are a fully preventable outage.
Interview tip โ Use SNI (server_hostname), or you get the wrong certificate on shared hosts.
Q68 A Python service in a container takes 30 seconds to stop during deploys. What do you look at?
Intermediate
Situation read โ The process is not handling SIGTERM, so it waits for SIGKILL after the grace period.
What I'd do โ
- Check the Dockerfile uses exec-form
ENTRYPOINT ["gunicorn", ...], not a shell form where/bin/shis PID 1 and swallows signals. - Confirm the app or server handles SIGTERM (gunicorn and uvicorn do; custom loops need a handler).
- For custom workers, install a
signal.signal(signal.SIGTERM, ...)handler that stops accepting work and exits. - Use
tini(docker run --init) if the app spawns children.
Why โ Proper signal handling means fast, graceful shutdowns and no dropped requests.
Interview tip โ "Shell-form CMD makes sh PID 1" is the usual root cause.
Q69 You want to build a Docker image from Python in CI and push it to ECR. What does the script need?
Intermediate
Situation read โ Auth to ECR plus build and push.
What I'd do โ
- Get a token:
ecr.get_authorization_token()returns base64AWS:<password>and the proxy endpoint. docker.from_env().login(username="AWS", password=pw, registry=endpoint).- Build with
images.build(path=".", tag=f"{repo}:{sha}")(or shell out todocker buildx buildfor BuildKit features), thenimages.push(repo, tag=sha, stream=True, decode=True)and check each line forerror. - In GitHub Actions, the official
aws-actions/amazon-ecr-loginplusdocker/build-push-actionis simpler.
Why โ The push stream reports errors inline; ignoring it hides failures.
Interview tip โ Mention checking the push stream for errorDetail.
Q70 You need an inventory of all EC2 instances turned into an Ansible dynamic inventory. Python script or plugin?
Beginner
Situation read โ Ansible already ships this.
What I'd do โ
- Use the
amazon.aws.aws_ec2inventory plugin withkeyed_groupson tags andfilters. - Only write a custom script if the source is something without a plugin (a CMDB API), outputting JSON with
_meta.hostvarsfor--list.
Why โ The maintained plugin handles pagination, caching and regions.
Interview tip โ Knowing the plugin exists is the point.
Q71 A script needs to run a long command on remote hosts and survive your laptop disconnecting. How do you design it?
Intermediate
Situation read โ Long-running remote work tied to a local SSH session dies with the session.
What I'd do โ
- Do not keep the work in the SSH session: start it as a systemd transient unit (
systemd-run --unit=reindex ...) or insidetmux/nohup, and poll status. - Better: run the orchestration from a CI job or a bastion, not a laptop.
- On AWS, SSM Run Command keeps running independent of your client and stores output.
Why โ Remote work should not depend on the controller's network.
Interview tip โ systemd-run is a neat, less-known answer.
Q72 You want to expose a small Python service that reports deployment versions of all services in the cluster. How do you build it?
Intermediate
Situation read โ Read-only internal API backed by the Kubernetes API.
What I'd do โ
- FastAPI app with
/versionsthat lists Deployments and returns image tags per container. - Cache results for 30 seconds (or use a watch to keep an in-memory cache) to avoid hammering the API server.
- In-cluster config with a service account allowed
listondeploymentsonly. /healthz,/readyz,/metrics; run under uvicorn with 2 workers behind a ClusterIP Service.
Why โ Caching protects the API server; scoped RBAC limits exposure.
Interview tip โ Mention caching; naive per-request list calls on large clusters hurt the control plane.
Q73 You discover a Python tool mounts /var/run/docker.sock into its container to list containers. What is the risk and alternative?
Advanced
/var/run/docker.sock into its container to list containers. What is the risk and alternative?Situation read โ Docker socket access equals root on the host.
What I'd do โ
- Explain: anyone who compromises the tool can start a privileged container mounting
/and own the host. - Alternatives: use the Kubernetes API (on k8s), cAdvisor or node metrics for read-only data, or a socket proxy (
docker-socket-proxy) allowing onlyGET /containers. - If unavoidable, run the tool isolated, read-only root, minimal network, and audited.
Why โ Least privilege applies to sockets too.
Interview tip โ Say "docker.sock is root" in the first sentence.
Q74 You need to compare installed package versions across 100 servers to find drift. How?
Beginner
Situation read โ Fleet query plus diff.
What I'd do โ
- Collect
rpm -qa --qf '%{NAME} %{VERSION}-%{RELEASE}\n'ordpkg-query -Wvia Fabric/SSM. - Parse into
{host: {pkg: version}}, find packages whose version set across hosts has more than one value. - Output a CSV of package, versions and host counts.
- Long term: immutable images (AMIs/containers) so drift cannot happen.
Why โ Drift detection points to the real fix: immutable infrastructure.
Interview tip โ End with immutability.
Q75 You need to watch for EC2 instance state changes and post to Slack in near real time. What do you build?
Intermediate
Situation read โ Event-driven, not polling.
What I'd do โ
- EventBridge rule on
EC2 Instance State-change Notificationtargeting a Python Lambda. - Lambda reads
detail.instance-idanddetail.state, looks up theNameandOwnertags withdescribe_instances, posts to Slack. - Slack webhook URL in Secrets Manager, cached across invocations.
- DLQ and retry settings on the target.
Why โ Events cost nothing when idle and arrive within seconds; polling wastes API calls.
Interview tip โ "Event-driven over polling" is the principle.
Testing, CI/CD, packaging & services
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q76 You join a team whose Python automation repo has no tests. Where do you start?
Beginner
Situation read โ Untested code that touches infrastructure.
What I'd do โ
- Add pytest, ruff and mypy to CI first, even with few tests, so the bar can only go up.
- Write tests for the most destructive scripts first (cleanup, deletion), using moto and dry-run assertions.
- Add a test with every bug fix that reproduces the bug.
- Refactor big scripts into pure functions as you touch them.
Why โ Risk-first testing gives the most protection per hour.
Interview tip โ "Test the scripts that delete things first."
Q77 Your pytest suite takes 12 minutes. How do you speed it up?
Intermediate
Situation read โ Usually network calls, sleeps, or expensive setup repeated per test.
What I'd do โ
pytest --durations=20to find the slowest tests.- Remove real network and
time.sleep(mock clocks, mock retries, set backoff to zero in tests). - Widen fixture scope for expensive, read-only setup (session-scoped containers).
- Run in parallel with
pytest-xdist(-n auto), ensuring tests are independent. - Split slow integration tests behind a marker (
-m "not integration") for PRs.
Why โ Most slow suites are a few slow tests; measure first.
Interview tip โ --durations is the first command to name.
Q78 A test passes locally but fails in CI only when run with the rest of the suite. What do you suspect?
Intermediate
Situation read โ Test pollution: shared state leaking between tests.
What I'd do โ
- Run with random order (
pytest-randomly) and bisect:pytest -p no:randomly tests/test_a.py tests/test_b.py. - Look for module-level state, singletons, cached clients created at import, env vars set without
monkeypatch, and files written outsidetmp_path. - With moto, look for clients created outside
mock_aws(they hit real endpoints or a different mock).
Why โ Order-dependent tests are always shared-state bugs.
Interview tip โ Mention clients created at import time, a frequent moto pitfall.
Q79 You want a reusable CI pipeline for 15 Python tool repos. What goes in it?
Intermediate
Situation read โ Standardize quality gates once.
What I'd do โ
- A reusable GitHub Actions workflow (
workflow_call) with inputs for Python version and package path. - Steps: checkout,
actions/setup-pythonwith pip cache (orastral-sh/setup-uv), install from lock,ruff check,ruff format --check,mypy,pytest --cov,pip-audit, build wheel. - Build and scan the Docker image (Trivy) where applicable; push on main with SHA tags.
- Pin actions by SHA; least-privilege
permissions:.
Why โ One pipeline definition means consistent gates and one place to fix things.
Interview tip โ Mention pinning third-party actions by commit SHA.
Q80 Your Python Docker image is 1.1 GB. How do you shrink it?
Intermediate
Situation read โ Full base image, build tools, caches and tests shipped to production.
What I'd do โ
python:3.12-sliminstead ofpython:3.12; avoid Alpine unless all deps have musllinux wheels.- Multi-stage: build a wheel (or venv) in a builder stage with compilers, copy only the result to the runtime stage.
pip install --no-cache-dir;.dockerignorefor.git,.venv, tests, caches.- Install only runtime deps, not
[dev]. - Measure with
docker historyordive.
Why โ Most size is the base and build toolchain; multi-stage removes both.
Interview tip โ Explain why Alpine can make Python images slower to build and sometimes bigger.
Q81 You want to distribute an internal CLI to 200 engineers. What are your options?
Intermediate
Situation read โ Distribution plus updates.
What I'd do โ
- Publish a wheel to an internal index (CodeArtifact, Artifactory); engineers install with
pipx install acme-opsoruv tool install acme-opsand upgrade the same way. - Also publish a Docker image for CI and for people who do not want Python locally.
- Version with semver and a changelog; add a "new version available" check if needed.
- Single-file options (
shiv,pex, PyInstaller) for environments without Python.
Why โ pipx/uv keep each tool isolated and upgradable.
Interview tip โ pipx is the expected answer for CLI distribution.
Q82 A Flask app runs with app.run() in production and falls over under load. What do you change?
Beginner
app.run() in production and falls over under load. What do you change?Situation read โ The development server is single-process and not built for production.
What I'd do โ
- Run under gunicorn:
gunicorn -w 4 -k gthread --threads 4 -b 0.0.0.0:8000 --timeout 30 app:app. - Size workers to CPU (roughly 2 x cores + 1 as a start) and measure.
- Put it behind a reverse proxy or load balancer; add health endpoints.
- Set
--graceful-timeoutand handle SIGTERM for clean deploys.
Why โ A real WSGI server handles concurrency, worker restarts and timeouts.
Interview tip โ Mention the dev server warning itself says not to use it in production.
Q83 You need a webhook receiver for GitHub that triggers deployments. Design it.
Advanced
Situation read โ Public endpoint that can deploy to production.
What I'd do โ
- FastAPI or Flask endpoint verifying
X-Hub-Signature-256with HMAC-SHA256 over the raw body andhmac.compare_digest. - Filter events (
X-GitHub-Event: pushonrefs/heads/main, orreleasepublished). - Deduplicate on
X-GitHub-Delivery; enqueue a job and return 202 within GitHub's 10-second timeout. - A worker performs the deploy idempotently and reports status back (commit status or deployment API).
- Restrict ingress to GitHub's published hook IP ranges (from
api.github.com/meta) as an extra layer.
Why โ Signature, dedupe, and async processing are the three properties a deploy webhook needs.
Interview tip โ Ask whether a pull-based model (Argo CD) removes the need for an inbound webhook.
Q84 You need to add Prometheus metrics to a Python batch job that runs every 10 minutes. How?
Intermediate
Situation read โ Short-lived process; Prometheus cannot scrape it reliably.
What I'd do โ
- Use a dedicated
CollectorRegistry, recordjob_duration_seconds,job_items_processed_totalandjob_last_success_timestamp_seconds. push_to_gateway("pushgateway.monitoring:9091", job="reconciler", registry=reg)at the end (also on failure, with a failure gauge).- Alert:
time() - job_last_success_timestamp_seconds > 1800. - If it runs on a host with node exporter, the textfile collector is an alternative.
Why โ Pushgateway is designed for batch jobs; the last-success timestamp catches every failure mode.
Interview tip โ Say Pushgateway is only for batch jobs, not for services.
Q85 How would you add type hints to a 5,000-line untyped automation codebase without stopping feature work?
Advanced
Situation read โ Gradual typing.
What I'd do โ
- Add mypy to CI with a permissive baseline (
ignore_missing_imports, nostrict), so it runs and passes. - Enable stricter settings per module with
[[tool.mypy.overrides]], starting with core modules and new code (disallow_untyped_defs). - Add
boto3-stubsandtypes-requests/types-PyYAMLfor library types. - Type function signatures first; inference handles most locals.
- Ratchet: new modules must be strict.
Why โ Gradual adoption delivers value immediately without a big-bang rewrite.
Interview tip โ Mention per-module overrides; it is how real teams do it.
Q86 Your team wants to move from pip + requirements.txt to uv. What do you evaluate?
Intermediate
pip + requirements.txt to uv. What do you evaluate?Situation read โ Tooling change; benefits are speed and a real lock file.
What I'd do โ
- Measure current CI install time vs
uv pip syncoruv sync. - Check compatibility: private indexes and auth, platform-specific wheels, Dependabot/Renovate support for
uv.lock. - Migrate one repo:
pyproject.tomlwith dependencies,uv lock, CI withastral-sh/setup-uvand cache. - Keep
uv export --format requirements-txtavailable for consumers that need it.
Why โ Measured pilots avoid tooling churn for its own sake.
Interview tip โ Mention that uv can also install Python itself, replacing pyenv in CI.
Q87 A tool must read secrets at runtime in both GitHub Actions and EKS. How do you design secret loading?
Intermediate
Situation read โ Same code, different environments.
What I'd do โ
- The code reads configuration from environment variables only (
pydantic-settingsmodel). - In GitHub Actions, secrets come from OIDC + Secrets Manager (
aws secretsmanager get-secret-valueor the official action) into env vars, masked. - In EKS, External Secrets Operator syncs Secrets Manager into a Kubernetes Secret mounted as env.
- The tool never knows where the secret came from.
Why โ Environment-agnostic code with platform-specific injection keeps the tool simple and testable.
Interview tip โ "Twelve-factor config" is the reference to make.
Q88 You need to test a function that calls subprocess.run(["terraform", "plan"]). How?
Intermediate
subprocess.run(["terraform", "plan"]). How?Situation read โ Do not run Terraform in unit tests.
What I'd do โ
- Patch
subprocess.runwhere it is used:monkeypatch.setattr(mymod.subprocess, "run", fake_run), returning asubprocess.CompletedProcess(args, 2, stdout=..., stderr=""). - Test parsing and decision logic for each return code (0 no changes, 2 changes with
-detailed-exitcode, 1 error). - Assert the exact arguments passed.
- A separate integration test can run real Terraform against a local backend.
Why โ Unit tests check your logic; integration tests check the tool.
Interview tip โ Mention -detailed-exitcode semantics.
Q89 Code review shows except Exception as e: logger.error(e) everywhere in a new tool. What feedback do you give?
Beginner
except Exception as e: logger.error(e) everywhere in a new tool. What feedback do you give?Situation read โ Errors are swallowed and tracebacks lost.
What I'd do โ
- Catch specific exceptions where you can handle them (
ClientErrorwith a specific code,FileNotFoundError). - Use
log.exception(...)to keep the traceback, and add context (which resource, which region). - Re-raise or exit non-zero when you cannot recover.
- Keep one broad catch at the CLI entry point that logs and exits 1.
Why โ Swallowed exceptions make tools report success while failing.
Interview tip โ "Catch narrow, log with context, fail loudly."
Q90 You want contract tests for an internal REST API your scripts depend on. What do you do?
Advanced
Situation read โ Your scripts break when the API changes shape.
What I'd do โ
- Validate responses against the API's OpenAPI schema in a scheduled integration test (
jsonschemaorschemathesis). - Model responses with pydantic in the client, so shape changes fail loudly at the boundary.
- Record real responses as fixtures (sanitized) for unit tests with
responses. - Agree on versioning with the API team; consumer-driven contracts (Pact) if the relationship is critical.
Why โ Boundary validation turns silent data bugs into clear errors.
Interview tip โ Mention pydantic models as runtime contracts.
Q91 You must make a FastAPI service production-ready for Kubernetes. What is your checklist?
Advanced
Situation read โ From "works locally" to operable.
What I'd do โ
- Run with uvicorn (or gunicorn with uvicorn workers), exec-form entrypoint, non-root user, slim image.
/healthz(no dependencies) and/readyz(dependencies with short timeouts) wired to probes.- JSON logs to stdout with request IDs;
/metricswith request count and latency histograms. - Graceful shutdown: handle SIGTERM, a
preStopsleep for endpoint propagation. - Resource requests and limits, config from env, secrets from a secret store.
- Timeouts on every outbound call.
Why โ These are the properties every reliable service on Kubernetes needs.
Interview tip โ The preStop sleep detail shows deep Kubernetes knowledge.
Q92 Your scheduled audit in GitHub Actions should fail the workflow on critical findings but still upload the report. How do you wire it?
Intermediate
Situation read โ Need the artifact even when the step fails.
What I'd do โ
- Give the audit step an
idandcontinue-on-error: true. - Upload the report with
actions/upload-artifact@v4andif: always(); write the Markdown report to$GITHUB_STEP_SUMMARY. - A final step fails the job if
steps.audit.outcome == 'failure'.
Why โ Separating "run" from "judge" keeps evidence even on failure.
Interview tip โ Our lab workflow uses exactly this pattern.
Q93 Your Python app's latency spikes every few minutes. Prometheus shows the spikes line up with high GC activity. What do you investigate?
Advanced
Situation read โ Garbage collection pauses or memory pressure.
What I'd do โ
- Check the
python_gc_collections_totalandprocess_resident_memory_bytesmetrics thatprometheus_clientexports by default. - Profile allocations with
tracemallocsnapshots ormemrayin staging. - Look for large object graphs created per request (caching whole API responses, huge dict copies).
- Tune
gc.freeze()after startup for pre-fork servers, or adjust thresholds, only after fixing allocation hot spots. - Check CPU throttling from container limits, which can masquerade as GC pauses.
Why โ Allocation reduction fixes GC pauses; tuning only hides them.
Interview tip โ Mention CPU throttling; it is a common confounder in containers.
Q94 A teammate wants to put business logic in a 400-line GitHub Actions YAML with inline Bash. You suggest Python. How do you justify it?
Beginner
Situation read โ Logic in YAML is untestable and hard to debug.
What I'd do โ
- Move logic into a Python module in the repo with a CLI, tested with pytest.
- The workflow just calls
python -m tools.release --version ${{ github.ref_name }}. - Same tool runs locally for debugging.
Why โ Testable, reviewable, runnable locally, portable across CI systems.
Interview tip โ "Keep pipelines thin, put logic in versioned code."
Q95 You need to guarantee that a Python service's dependencies are exactly what was tested. What do you do?
Advanced
Situation read โ Reproducibility and supply-chain integrity.
What I'd do โ
- Lock all dependencies, including transitive, with hashes (
pip-compile --generate-hashesoruv lock). - Install with
pip install --require-hashes --no-deps -r requirements.txt(oruv sync --frozen) in the image build. - Build the image once, test that image, promote the same digest to production.
- Generate an SBOM (Syft) and scan (Trivy/Grype); sign the image (cosign).
Why โ Hashes stop tampered packages; promoting the same digest guarantees "tested == deployed".
Interview tip โ "Build once, promote by digest" is the key line.
Q96 How would you write an integration test that runs your Docker image against moto in CI?
Advanced
Situation read โ Test the packaged artifact end to end without AWS.
What I'd do โ
- Start moto as a server:
docker run -d -p 5000:5000 motoserver/motoas a service container. - Seed resources with boto3 pointed at
endpoint_url="http://localhost:5000". - Run the image with
-e AWS_ENDPOINT_URL=http://host:5000 -e AWS_ACCESS_KEY_ID=x -e AWS_SECRET_ACCESS_KEY=x -e AWS_DEFAULT_REGION=us-east-1; recent boto3 honoursAWS_ENDPOINT_URLwithout code changes. - Assert exit code and report content.
Why โ Catches packaging bugs (missing modules, wrong entrypoint) that unit tests cannot.
Interview tip โ Mention AWS_ENDPOINT_URL; it removes the need for test-only code paths.
Q97 You need a lightweight internal dashboard of audit results. Do you build a Flask app?
Beginner
Situation read โ Probably not; a static report may be enough.
What I'd do โ
- Generate a static HTML or Markdown report in the audit job and publish to S3 + CloudFront (with auth) or GitHub Pages for private repos.
- Or push metrics (findings by severity) to Prometheus and use Grafana.
- Only build a Flask app if users need interactivity (filtering, acknowledging findings).
Why โ Static output has no server to patch or run.
Interview tip โ Choosing not to build a service is often the senior answer.
Q98 Your Python tool works in Docker on your laptop (arm64 Mac) but CI on x86 fails with exec format error. What happened?
Intermediate
exec format error. What happened?Situation read โ The image was built for arm64 and pushed, then run on amd64.
What I'd do โ
- Build multi-arch:
docker buildx build --platform linux/amd64,linux/arm64 -t repo:tag --push .. - Or build in CI on amd64 runners only and never push from laptops.
- Check with
docker manifest inspect repo:tagordocker buildx imagetools inspect.
Why โ Images are architecture-specific unless built as multi-arch manifests.
Interview tip โ Say "CI builds images, laptops don't push".
Q99 Product asks for a feature-flag check inside a deployment script. How do you keep the script from becoming fragile?
Beginner
Situation read โ External dependency in the deploy path.
What I'd do โ
- Wrap the flag service call in a small client with a timeout and a safe default (fail closed or open, decided explicitly).
- Cache the flag value for the duration of the run.
- Log the decision and the flag value.
- Unit-test both branches with a mocked client.
Why โ Deploys must not hang or break because a non-critical service is slow.
Interview tip โ Explicitly choosing fail-open vs fail-closed is what interviewers look for.
Q100 Walk me through how you would present the cloud-ops audit CLI from the lab in an interview.
Intermediate
Situation read โ Project storytelling: problem, design, trade-offs, results.
What I'd do โ
- Problem: no visibility into untagged/idle EC2, open security groups and old snapshots across regions.
- Design: click CLI, boto3 with paginators and adaptive retries, per-region threads with one Session each, findings as dataclasses, JSON/CSV/Markdown renderers, exit code 2 on HIGH findings.
- Quality: pytest with moto (offline, free), ruff, mypy strict, Docker multi-stage non-root.
- Operations: weekly GitHub Actions run via OIDC with a read-only role, report as artifact and job summary.
- Trade-offs: moto gaps (snapshot timestamps) handled with stubs; "no metrics" treated as unknown, not idle.
Why โ Structure shows engineering judgment, not just code.
Interview tip โ Always have one trade-off and one thing you would improve next ready.