Automation Scripting for Operations Questions
Writing scripts and tooling to automate operational and delivery tasks: shell and Python scripting, glue automation, toil reduction, and operational efficiency. Covers automating repetitive infrastructure and deployment work and building internal tooling that raises operational leverage. The concern is task-level automation and scripting, distinct from full pipeline or infrastructure-as-code frameworks.
Design monitoring and alerting for a fleet of scheduled automation jobs. What health metrics would you collect to know a job is actually healthy, what alerting thresholds would you set to avoid paging noise, how would escalation and runbook integration work, and where might automated remediation be safe to attempt for transient failures?
Sample Answer
Direct answer
Monitoring a FLEET of scheduled jobs is a different problem from monitoring one job: the goal is surfacing the few jobs that are actually unhealthy out of potentially hundreds that are fine, without burying the signal in noise.
Health metrics to collect
Per job: success rate over a rolling window (not just 'did the last run succeed' -- a job that fails 1 run in 20 looks different from one that just started failing every run), duration (and duration trend -- a job that's gradually getting slower is an early warning before it eventually times out), last-run timestamp (is this job even firing on schedule, or silently stopped triggering entirely), retry count per run (a job succeeding only after 3 retries every time is degraded even though it's technically 'succeeding'), and jitter (how much actual fire-time deviates from scheduled time, which surfaces scheduler-level problems separate from the job's own logic).
Alerting thresholds that avoid noise
Alert on SUSTAINED or TREND signals, not single-run blips: a job that fails once and succeeds on its next scheduled run is not worth paging anyone about (that's exactly what retry/backoff exists to absorb); a job failing its last 3 consecutive runs, or a job whose success rate drops below some threshold (e.g. 90%) over a rolling window, is a real signal. Separate paged (wake someone up) from non-paged (a dashboard/ticket, reviewed during business hours) by actual urgency -- a nightly backup job failing has hours before it matters; a job gating an active deployment failing needs to page immediately.
Escalation flow and runbook integration
A page should link DIRECTLY to that job's specific runbook (not a generic 'automation is broken, good luck' page) -- the runbook should cover the common failure modes for that specific job class (dependency down, resource exhaustion, a known-flaky external API) and the safe manual remediation steps. Escalate to a secondary on-call if the primary doesn't acknowledge within a defined window, and auto-resolve the page if the job self-recovers on its next scheduled run rather than requiring a human to manually close it.
Auto-remediation for transient failures
Safe candidates for automated remediation: a job that fails due to a transient, well-understood cause (a known-flaky dependency that recovers on its own) can have an automatic extra retry attempt beyond its normal retry policy, with a page only firing if THAT also fails. Riskier or ambiguous failures (anything that could indicate a real logic bug, or anything destructive) should never auto-remediate -- auto-remediation is appropriate only when you're confident re-running the exact same job with the exact same inputs is safe (idempotent) and the failure class is well-understood enough that blind retrying isn't masking a real, worsening problem.
Worked example: a nightly backup job
Applying this design to one specific job: track success rate (page if 2 consecutive nightly runs fail), duration (warn, don't page, if a run takes 50% longer than its 30-day rolling average -- an early signal before it eventually breaches a hard timeout), and snapshot size (a suspiciously small backup can indicate the source data wasn't actually captured, a silent-failure mode plain success/failure status won't catch). The runbook for this job should explicitly cover 'how to verify the backup is actually restorable,' not just 'how to re-run it,' and alerting should be tested periodically (deliberately break the job in staging) rather than trusted to work correctly just because it was configured once.
Trade-offs and pitfalls
The most common mistake is measuring toil-reduction success purely by count of automations shipped rather than by actual adoption and hours genuinely saved -- a platform team incentivized on shipped-automation count will optimize for easy, low-value wins rather than the highest-impact toil identified by the prioritization framework above. Edge case: a task that LOOKS automatable but has a rare, high-judgment exception baked into how humans currently handle it (an edge case that occurs 1% of the time but needs real judgment) can produce an automation that's net-negative if that exception isn't explicitly carved out and routed to a human.
You need to design a CLI for a cross-team automation tool that manages backups and restores. Specify top-level commands, expected flags (global and per-command), help/usage patterns, standard exit codes, logging verbosity flags, and how to design an idempotent --dry-run mode. Mention recommended libraries for Python and Go and describe how to handle configuration precedence (CLI args, env vars, config file).
Sample Answer
Direct answer
A cross-team CLI earns trust the same way a good API does: predictable structure, safe defaults, and no surprises. The two commands (backup, restore) should be subcommands of one binary, each with its own scoped flags, plus a small set of global flags that apply everywhere.
Command surface
backuptool [global flags] <command> [command flags]
Global flags:
--verbose, -v increase log verbosity (repeatable: -vv)
--dry-run show what would happen, make no changes
--config PATH explicit config file path
--output json|text machine-readable vs human-readable output
Commands:
backup --target NAME [--full|--incremental] [--retention DAYS]
restore --target NAME --snapshot ID [--to PATH]
list [--target NAME] # discoverability: what CAN I restore?
status [--run-id ID] # is a backup/restore in flight, did it succeed?
list and status aren't in the original ask but are worth calling out explicitly: a tool that can only DO things and never tell you what it's already done gets treated as a black box, and operators route around black boxes.
Exit codes and help
Use the conventional split: 0 success, 1 for a runtime failure (the operation was attempted and failed), 2 for a usage error (bad flags -- the operation was never attempted). This distinction matters operationally: a wrapper script or a monitoring check needs to tell 'you typo'd a flag' apart from 'the backup actually failed', and a single generic non-zero exit code collapses that distinction. Every command needs -h/--help text with at least one example invocation; a flag list with no example is where most CLI usability complaints come from.
Idempotent --dry-run
--dry-run should exercise the exact same code path as a real run up to (and not including) the side-effecting step, so what it prints is genuinely what would happen, not a separately-maintained approximation that can drift out of sync. Concretely: build the full plan (which files, which destination, computed retention actions), print the plan, and return before calling anything that mutates state. This is 'idempotent' in the sense that running --dry-run a hundred times in a row changes nothing and always shows the same plan for the same inputs -- if it isn't, the dry-run path has drifted from the real path and can no longer be trusted.
Config precedence
Standard, least-surprising order (highest wins): explicit CLI flag > environment variable > config file > built-in default. Document this order once, prominently, because 'why didn't my env var take effect' is the single most common CLI support question, and it's almost always a precedence surprise.
Libraries
Python: argparse (stdlib, sufficient for subcommands) or click/typer for richer UX with less boilerplate. Go: the standard library's flag package is thin; cobra (used by kubectl, docker CLI) is the de facto standard for subcommand-heavy tools and is a defensible default recommendation for a cross-team tool that other engineers will extend.
Trade-offs and pitfalls
The most common mistake is over-fitting the CLI's flags to whatever the FIRST team that adopts it needs, then discovering every subsequent team wants a slightly different flag shape for the same underlying concept -- naming flags around the general operation (--target, --source) rather than one team's specific vocabulary pays off once the tool is genuinely cross-team. Edge case: a flag that's valid for one subcommand but silently ignored (not rejected) for another is a common source of confused bug reports; validate flag-subcommand compatibility explicitly rather than letting argparse accept anything globally-defined everywhere.
Implement a Python function 'http_get_with_retry(url: str, max_attempts: int = 5, timeout: int = 10)' that performs an HTTP GET using the 'requests' library and retries on transient network errors and 5xx responses. Use exponential backoff with jitter between retries, and ensure you do not retry on 4xx client errors that are permanent. If 'tenacity' is available you may outline how to use it; otherwise implement the retry loop yourself. Keep the function idempotent and allow caller to configure max_attempts and timeout.
Sample Answer
Approach
The function needs to distinguish 'this failure might succeed if I try again' (network errors, 5xx) from 'this failure will fail identically every time' (a 4xx client error), and only retry the former.
import random
import time
import requests
def http_get_with_retry(url: str, max_attempts: int = 5, timeout: int = 10):
last_exc = None
for attempt in range(1, max_attempts + 1):
try:
resp = requests.get(url, timeout=timeout)
except requests.exceptions.RequestException as e:
last_exc = e
else:
if resp.status_code < 400:
return resp
if 400 <= resp.status_code < 500:
resp.raise_for_status() # permanent client error, do not retry
last_exc = requests.exceptions.HTTPError(
f"server error {resp.status_code}", response=resp)
if attempt < max_attempts:
ceiling = min(8.0, 0.5 * (2 ** (attempt - 1)))
time.sleep(random.uniform(0, ceiling)) # full jitter
raise last_exc
Verified against a fake session in a sandbox with two scenarios: (1) two consecutive 503 responses followed by a 200 -- the function returns the 200 after exactly 3 calls; (2) a single 404 -- the function raises immediately after exactly 1 call, confirming it does not retry a permanent client error.
Idempotency
A plain GET is idempotent by definition (it has no side effects to duplicate), which is exactly why this function is safe to retry unconditionally on transient failures without needing an idempotency token -- that requirement only bites for POST/PUT/DELETE-style calls with side effects, which is out of scope for this specific function but worth naming so it's clear why this case is simpler.
The 'tenacity' alternative
If the tenacity library is available, the same behavior is declarative rather than hand-rolled:
from tenacity import retry, stop_after_attempt, wait_random_exponential, retry_if_exception_type
@retry(stop=stop_after_attempt(5),
wait=wait_random_exponential(multiplier=0.5, max=8),
retry=retry_if_exception_type(requests.exceptions.ConnectionError))
def http_get_with_retry(url, timeout=10):
resp = requests.get(url, timeout=timeout)
resp.raise_for_status()
return resp
This is less code and battle-tested, but note it needs retry_if_exception_type (or a custom predicate) tuned so it doesn't also retry the HTTPError raised by 4xx responses -- the hand-rolled version's explicit status-code branch is arguably clearer about that distinction than composing tenacity's exception-type matching correctly.
Trade-offs and pitfalls
The most common bug in this exact function shape is putting resp.raise_for_status() before the status-code branching, which turns EVERY non-2xx response (4xx included) into the same generic exception the retry loop then treats as retryable -- silently defeating the whole point of excluding 4xx. Keep the 4xx/5xx distinction as an explicit branch, not something inferred later from exception type alone.
Edge cases: a Retry-After header on a 429 response (if the server sends one) should generally be honored over the computed backoff delay, since the server is telling you exactly how long to wait rather than leaving you to guess; a max_attempts=1 call should make exactly one attempt with no retry loop overhead at all, worth testing explicitly since off-by-one errors are common in exactly this boundary case.
You need to run a Python automation action across 500 hosts concurrently. Compare an approach building a custom runner using concurrent.futures + paramiko versus using an off-the-shelf orchestration tool like Ansible. Discuss scalability, inventory management, secrets distribution, retry behavior, idempotency, and how you would implement batching and failure isolation with the custom runner.
Sample Answer
Direct answer
At 500 hosts, the real question isn't 'which tool is technically capable' (both are), it's which one you want to own the operational complexity of: inventory management, secrets distribution, and failure isolation, versus building and maintaining that yourself.
Scalability and inventory management
Ansible's inventory system (static files, dynamic inventory scripts/plugins for cloud providers) is a mature, well-tested solution to 'which hosts, grouped how, with what per-group variables' -- a custom concurrent.futures + paramiko runner has to build this from scratch, and inventory management is a deceptively large surface (host groups, per-host overrides, dynamic discovery) to get right. At 500 hosts specifically, both approaches can technically execute concurrently at that scale; the difference is how much of the surrounding machinery (retry-per-host, connection pooling, structured per-host result reporting) you get for free versus have to build.
Secrets distribution
Ansible Vault (or integration with an external secrets manager via lookup plugins) has existing, audited patterns for distributing credentials to a fleet without them landing in plaintext on every target host. A custom runner needs to solve this itself -- likely reusing the secrets-handling patterns discussed elsewhere in this topic (short-lived credentials fetched per-connection rather than distributed and stored), which is very doable but is additional design and implementation surface Ansible gives you largely for free.
Retry behavior and idempotency
Ansible's module system is BUILT around idempotency as a first-class concept -- most built-in modules check current state before acting and report 'changed' vs 'ok' accordingly, which is exactly the idempotency discipline this whole topic argues for, already baked into the tool. A custom runner running an arbitrary script over SSH has NO such guarantee -- idempotency (or the lack of it) is entirely a property of whatever script you're running, and the runner itself only adds retry-on-connection-failure, not retry-safety for the underlying operation.
When the custom runner is still the right call
Despite Ansible's advantages above, a custom concurrent.futures + paramiko runner is justified when: the operation is a one-off, tightly-scoped action that doesn't fit Ansible's declarative module model well; you need custom batching/failure-isolation logic Ansible's default execution strategy doesn't offer out of the box (e.g., 'stop launching new batches immediately if failure rate exceeds 10%, but let in-flight batches finish'); or the team is already deep in a Python-based automation framework (per the language-choice discussion elsewhere in this topic) and adding Ansible as a second tool has its own onboarding/maintenance cost that isn't worth it for this one task.
Batching and failure isolation with a custom runner
If building custom: batch hosts into fixed-size groups (e.g. 50 at a time) submitted to a bounded ThreadPoolExecutor, track per-host success/failure independently (one host's connection failure must never abort or block the others), and implement a circuit-breaker-style check between batches -- if failure rate in the last batch crosses a threshold, pause and surface to an operator rather than blindly continuing through all 500 hosts and only discovering a systemic problem (bad SSH key rotation, a network partition) after every host has already failed.
Trade-offs and pitfalls
The most common mistake building a custom runner is treating the FIRST version as sufficient to reach production without the retry, secrets, and failure-isolation depth Ansible already has -- what starts as 'this is simpler than learning Ansible' quietly grows into reimplementing large parts of it, worse and less tested, exactly the scope-creep risk the custom-vs-mature-tools trade-off discussed elsewhere in this topic warns about.
Explain idempotency in the context of operational automation and SRE scripts. Provide concrete examples of idempotent and non-idempotent operations, explain why idempotency matters for retries, scheduled jobs, and incident recovery, and list practical techniques (checks, CAS, temporary files, atomic renames) you'd use to make an automation idempotent.
Sample Answer
Direct answer
An operation is idempotent if running it once and running it N times leave the system in the same final state. For automation this matters enormously because scripts get re-run all the time -- by a retry, by a scheduler firing again after a crash, by an operator manually re-triggering a stuck job -- and if the operation isn't idempotent, a re-run doesn't just repeat the work, it corrupts the outcome.
Idempotent vs non-idempotent examples
- Idempotent:
UPDATE users SET status = 'active' WHERE id = 5(setting a value, not incrementing it); creating a file with fixed content via atomic write;PUTa resource with a full representation. - Non-idempotent:
INSERT INTO users (...) VALUES (...)with no uniqueness constraint (running it twice creates a duplicate row);UPDATE balance = balance + 100(running it twice adds 200); appending a line to a log file on every run (running it twice appends twice).
Why it matters for retries, scheduled jobs, and incident recovery
Retries only make sense as a resilience mechanism if re-attempting is safe -- otherwise every retry policy is trading 'might fail' for 'might silently double-apply,' which is worse. Scheduled jobs re-run on a fixed cadence regardless of whether the previous run's outcome is known, so if a job's own idempotency isn't guaranteed, a scheduler firing twice in quick succession (or a manual re-trigger after an ambiguous failure) can duplicate side effects. During incident recovery specifically, the person fixing things is often re-running a script under time pressure without being 100% sure the first run completed -- an idempotent script means 're-run it and see' is a safe troubleshooting step rather than a gamble.
Practical techniques
- Check-before-act: verify current state before mutating (does the user already exist? is the directory already present?) and skip if the desired state is already true.
- Compare-and-swap (CAS) / conditional writes: mutate only if the current value matches an expected prior value (an ETag check, a
WHERE version = Nclause), so a concurrent or repeated write can't silently clobber a change made in between. - Temporary files + atomic rename: write new content to a temp file, then
os.replace()/mvit into place -- the rename is atomic at the filesystem level, so a crash mid-write never leaves a half-written file for a re-run to see.
Worked example: package install and user account creation
Installing a package idempotently means checking 'is this package already at the target version' before running the installer, not blindly re-running apt install (which is itself usually idempotent, but a custom install script that unconditionally downloads-and-extracts is not -- a re-run mid-network-blip can leave a half-extracted package that the next run needs to detect and clean up, not just retry blindly on top of). Creating a user account idempotently means checking 'does this user already exist with these group memberships' before calling useradd, because a bare re-run of useradd bob on an already-existing bob fails loudly (which is actually the SAFE failure -- the dangerous version is a custom account-provisioning script that does useradd then unconditionally appends group memberships on every run, silently accumulating group memberships across genuinely legitimate re-runs rather than converging to a fixed desired-state list). Common pitfalls that break idempotency in practice: race conditions (two concurrent runs both pass the check-before-act check before either acts), partial failures (a crash between step 2 and step 3 of a 3-step operation leaves state a re-run doesn't correctly recognize as 'partially done'), and destructive cleanup steps (a re-run that deletes-then-recreates rather than checking-then-updating, which turns a benign re-run into a brief outage window every single time).
Trade-offs and pitfalls
The most common mistake is treating idempotency as binary (a script either 'is' or 'isn't' idempotent) rather than as a property that has to be verified for EACH distinct side effect a script has -- a script can correctly no-op on its main file write while still, say, unconditionally appending a log line on every run, making it only partially idempotent in a way that's easy to miss in review. Edge case: an operation that's idempotent under normal conditions can stop being idempotent under a specific failure mode (a crash between two of its steps) if those steps aren't ALSO individually and jointly idempotent -- idempotency has to be verified end-to-end, not just for the common-path run.
Unlock Full Question Bank
Get access to all 49 Automation Scripting for Operations interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.