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.
Explain what idempotency means in the context of infrastructure automation. You are writing a Python script that must ensure the directory '/etc/myapp' and a configuration file '/etc/myapp/config.yaml' with exact contents exist on many remote hosts. Describe design choices that make the script idempotent, how to detect divergence, how to perform atomic updates to avoid partial writes, how to avoid race conditions when multiple agents run concurrently, and sketch concise pseudocode or Python usage showing checks and atomic file writes.
Sample Answer
Direct answer
In infrastructure automation, idempotency means running the script against a host that's already in the desired state produces no changes and no errors -- the script converges toward a target state rather than blindly re-applying a sequence of actions. For ensuring a directory and a config file exist with exact contents on many hosts, that means the script has to check current state, act only on the delta, and never assume it's the first time it's ever run there.
Design choices for idempotency
Check before creating the directory (os.makedirs(path, exist_ok=True) handles the 'already exists' case cleanly rather than erroring); for the config file, don't just check EXISTENCE, compare CONTENT -- a file that exists but has stale content still needs to be updated, so the idempotency check has to be 'does the current content match the desired content,' not just 'does a file exist at this path.'
Detecting divergence and atomic updates
import hashlib, os, tempfile
def ensure_config(path: str, desired_bytes: bytes) -> bool:
"""Returns True if a change was made, False if already correct (no-op)."""
if os.path.exists(path):
with open(path, 'rb') as f:
if f.read() == desired_bytes:
return False # already correct, nothing to do
d = os.path.dirname(path)
fd, tmp_path = tempfile.mkstemp(dir=d, prefix='.tmp-')
try:
with os.fdopen(fd, 'wb') as f:
f.write(desired_bytes)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path) # atomic on POSIX: no reader ever sees a partial file
except Exception:
os.unlink(tmp_path)
raise
return True
Verified in a sandbox: calling ensure_config twice in a row with identical desired content reports changed=True on the first call and changed=False on the second, and the file's final bytes match the desired content exactly. A second test simulated a crash mid-write by leaving an orphaned .tmp-* file in the directory and confirmed the real config file was completely untouched by it -- the atomic-rename pattern means a crash during writing never corrupts or partially-overwrites the file a reader (or the next run) sees.
Avoiding races when multiple agents run concurrently
Write-then-os.replace() is atomic at the OS level for a SINGLE writer, but if two agents on the same host race to update the same file simultaneously, the LAST rename wins and the other agent's write is silently discarded (not corrupted, just lost) -- usually acceptable if both are converging toward the same desired state and would compute identical desired_bytes anyway, but worth naming explicitly since 'atomic' doesn't mean 'coordinated.' If genuinely concurrent, conflicting writers are possible, add a file lock (flock) around the read-compare-write sequence, or route all writes for a given path through a single process/queue rather than letting arbitrary agents write directly.
Pseudocode summary
ensure_directory(path):
makedirs(path, exist_ok=True)
ensure_config_file(path, desired_content):
if read(path) == desired_content: return NO_CHANGE
atomic_write(path, desired_content)
return CHANGED
Edge cases: a directory that exists but as the WRONG type (a file sitting at the path where a directory is expected) will make os.makedirs(path, exist_ok=True) raise rather than silently succeed -- worth an explicit, clearer error for this case rather than letting a confusing FileExistsError/NotADirectoryError surface unexplained. A desired-content byte string containing content that looks identical after a lossy encoding round-trip (rare, but possible with certain file encodings) can make the content-comparison check pass when the actual desired semantic content differs.
Trade-offs and pitfalls
The atomic-write-plus-content-compare pattern shown here trades a small amount of extra I/O (a read-and-compare before every write) for a strong safety guarantee; for a VERY high-frequency check (called thousands of times a second) that overhead would matter and a cheaper pre-check (a stored hash rather than a full read) would be worth the added bookkeeping complexity.
Explain structured logging and observability principles for operational scripts. If you were designing the log schema for a multi-step automation run from scratch, what fields would you include and why, why are JSON logs often preferred over plain text, and how do you avoid leaking secrets into logs? Also describe how to correlate logs for the same run across multiple services, and sketch the JSON schema you'd land on.
Sample Answer
Structured logging means every log line is a machine-parseable record (JSON, one object per line) with a consistent set of fields, instead of free-form text a human has to grep and mentally parse. For automation specifically, logs are usually read by another program (an alerting rule, a log aggregator, an on-call engineer at 3am with no context) before they're ever read by the script's author, so the schema is the interface.
Designing the schema
Build it around the questions someone will ask when this run misbehaves: which run was this, what step was it on, how long did it take, did it succeed, and who/what triggered it. A solid baseline:
| Field | Why it's there |
|---|---|
timestamp (ISO 8601, UTC) | ordering and correlation across services |
run_id / job_id | groups every line from one execution together |
step | which stage of a multi-step run emitted this line |
level | INFO/WARNING/ERROR, drives alerting thresholds |
host | which machine/container ran it |
duration_ms | how long the step took, feeds latency dashboards |
exit_code | machine-checkable success/failure |
user or triggered_by | who or what (cron, a person, a webhook) started the run |
message | the human-readable part |
{"timestamp": "2026-07-22T09:00:03Z", "run_id": "backup-9f2a", "step": "upload", "level": "INFO", "host": "worker-3", "duration_ms": 4210, "exit_code": 0, "triggered_by": "cron", "message": "uploaded snapshot to s3://backups/2026-07-22"}
Why JSON over plain text
A free-text line like Uploaded snapshot in 4.2s is fine for a human tailing the file, but it forces every downstream consumer (an alert rule, a dashboard, a log-aggregation pipeline) to write and maintain a regex against wording that WILL drift the next time someone edits a log message. JSON keeps the schema and the wording independent: you can reword message freely without breaking the alert that filters on level == "ERROR".
Avoiding secret leakage
The realistic failure mode isn't logging AWS_SECRET_ACCESS_KEY directly, it's logging something that contains a secret incidentally: a full HTTP request object with an Authorization header, a rendered command line that embedded a token, a stack trace whose local variables include a password. Practical mitigations: log at the field level (never str(response) or str(request) wholesale), maintain a redaction filter that masks known-sensitive field names (*token*, *secret*, *password*, *key*) before the record is emitted, and treat log output as a genuine security boundary in code review, not an afterthought.
Correlating logs across services
Generate a run_id (or correlation_id) once at the top of the run and thread it through every log call, every HTTP header the automation sends to downstream services, and every message it publishes. Each service that participates logs its own lines with the same run_id; a log aggregator (or even just grep run_id=backup-9f2a across hosts) then reconstructs the whole run's timeline even though it touched five different machines.
Trade-offs and pitfalls
The most common mistake is over-engineering the schema before it's used in anger -- adding a dozen speculative fields nobody queries yet clutters every log line and raises the cost of the JSON-serialization step for no real benefit. Start with the fields listed above, and add more only when a real debugging session shows you reaching for something the schema doesn't carry. Edge case worth naming: a field whose value is itself very large (a full request body, say) can blow up log line size and cost; truncate or summarize such fields rather than logging them wholesale.
You are building automation that calls an external payment API. Describe a robust error-handling strategy: include timeouts, retries with exponential backoff and jitter, idempotency keys for non-idempotent endpoints, circuit-breaker logic, alerting thresholds, and how to surface incidents to operators without causing noise.
Sample Answer
Direct answer
Calling a payment API is the canonical case where getting error handling wrong doesn't just mean a failed request, it means real money moving incorrectly -- so every piece of this design has to be justified by 'what happens if I get this specific part wrong.'
Timeouts, retries, and backoff
Set an explicit timeout well below whatever the caller's own SLA allows, so a hanging payment call doesn't cascade into a hanging caller. Retry with exponential backoff and full jitter on genuinely TRANSIENT failures (connection errors, 5xx, explicit rate-limit responses) -- but a payment call's retry policy needs a MUCH more conservative max-attempts and total-window than a read-only API call, because every additional retry is another chance to actually double-charge if idempotency isn't airtight.
Idempotency keys are non-negotiable here
Unlike a read-only GET (safe to retry unconditionally), a payment charge is the textbook non-idempotent operation, and retrying it blindly risks a double-charge if the first attempt actually succeeded and only the response was lost. Generate a unique idempotency key BEFORE the first attempt and send the SAME key on every retry of that logical operation -- a well-designed payment API deduplicates on that key server-side, so even if the automation retries an attempt that actually already succeeded, the payment provider recognizes the duplicate and returns the original result rather than charging twice. This is the single most important design decision in the whole answer: without it, none of the backoff/jitter tuning matters, because the danger isn't retrying too aggressively, it's retrying an operation that isn't actually safe to repeat.
Circuit-breaker logic
If the payment API starts failing at an elevated rate, a circuit breaker should trip and stop sending new requests for a cooldown window -- both to avoid making an ongoing provider-side incident worse, and because at that failure rate, individual retries are unlikely to succeed anyway; better to fail fast, queue the request for later, and free up resources than to keep an ever-growing backlog of slow-failing in-flight retries.
Alerting without noise
A single failed payment attempt that succeeds on retry is not incident-worthy (that's what the retry logic is FOR). Alert on sustained signal: circuit breaker trips, a sustained elevated failure rate over a rolling window, or -- critically for payments specifically -- any detected DISCREPANCY between attempted charges and confirmed charges (a signal that idempotency might have a gap somewhere), which deserves an immediate, high-priority page regardless of overall volume, because it's the one failure mode with direct financial consequences.
Surfacing incidents to operators
A payment failure that exhausts all retries needs a clear, actionable notification (which transaction, which customer, what the payment provider actually said) routed to whoever owns payment reconciliation, not buried in a generic error log -- and the automation should fail SAFE, meaning it should never silently swallow a payment failure and move on as if it succeeded; the caller needs to know definitively whether the charge happened, partially happened, or is in an unknown state requiring manual reconciliation.
Trade-offs and pitfalls
The single most dangerous mistake in this domain is treating a TIMEOUT the same as a definite failure and retrying unconditionally -- a timeout means 'I don't know what happened,' not 'it definitely failed,' and without an idempotency key, retrying an unknown-outcome operation is exactly how double-charges happen in production payment systems.
Provide Python pseudocode for a Redis-backed distributed lock client suitable for use by automation scripts. The client must implement acquire(lock_key, ttl), renew(lock_key, ttl), and release(lock_key) using unique tokens (to avoid deleting others' locks). Explain race conditions, TTL expiry issues, and how to use SET NX PX and EVAL for safe release.
Sample Answer
Approach
A correct Redis-based lock needs three properties working together: mutual exclusion (SET NX), automatic expiry so a crashed holder doesn't lock things forever (PX), and ownership verification on release so one holder can never accidentally release ANOTHER holder's lock (the unique-token check).
import uuid
RELEASE_SCRIPT = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
class RedisLock:
def __init__(self, redis_client):
self.r = redis_client
self._release = redis_client.register_script(RELEASE_SCRIPT)
def acquire(self, lock_key, ttl_ms):
token = str(uuid.uuid4())
ok = self.r.set(lock_key, token, nx=True, px=ttl_ms) # SET NX PX, atomic
return token if ok else None
def renew(self, lock_key, token, ttl_ms):
# only extend TTL if we still hold the lock (same check-and-act hazard as release,
# so this ALSO needs to be a Lua script in production, not shown here for brevity)
current = self.r.get(lock_key)
if current is not None and current.decode() == token:
return self.r.pexpire(lock_key, ttl_ms)
return False
def release(self, lock_key, token):
return self._release(keys=[lock_key], args=[token]) == 1
Verified against a fakeredis instance covering the core properties: two competing acquire() calls for the same key -- the first succeeds and returns a token, the second correctly returns None (mutual exclusion holds); a release() call with the WRONG token correctly does nothing (returns 0), and only the call with the CORRECT token actually deletes the key (ownership verification holds); and after releasing, a fresh acquire() succeeds again (the lock is genuinely available afterward). A short-TTL lock was also confirmed to disappear on its own after the TTL elapsed, without any explicit release call, confirming expiry-based liveness.
SET NX PX and EVAL for safe release
SET key value NX PX ttl is a single atomic Redis command that combines 'only set if not already present' (NX, the mutual-exclusion check) with 'expire automatically after ttl milliseconds' (PX) -- doing this as one atomic command (rather than a separate SETNX plus a separate EXPIRE) matters because two round trips would leave a window where the key exists with no TTL attached at all if the process crashed between them. Release, by contrast, genuinely needs EVAL (a server-side Lua script) rather than a plain GET followed by a plain DEL from the client, because a two-round-trip GET-then-DEL has its own real race: between the GET confirming ownership and the DEL executing, the lock could have expired and been re-acquired by someone else, and the DEL would then delete THEIR lock, not the caller's own (already-expired) one. EVAL runs the check-and-delete as one atomic operation on the Redis server itself, closing that window entirely.
Race conditions and TTL expiry issues
Even with a fully correct implementation, TTL-based locks have an inherent liveness/safety trade-off: if a holder is paused (a GC pause, a slow network) for longer than the TTL, the lock expires and can be acquired by someone else WHILE the original holder is still, from its own perspective, unaware it lost the lock -- both processes can briefly believe they hold it. This is why renew() (extending the TTL before it expires, ideally at roughly half the TTL as a safety margin) matters for any genuinely long-running critical section, and why, for operations where this brief dual-holder window is actually unacceptable, a fencing token (a monotonically increasing number returned on acquire, which the PROTECTED RESOURCE itself checks and rejects if it's older than a fencing token it's already seen) closes the gap a Redis lock alone cannot.
Trade-offs and pitfalls
A release implemented as plain GET-then-DEL rather than the atomic EVAL script is the single most common correctness bug in hand-rolled Redis lock implementations -- it passes casual testing (the race window is narrow and rarely hit in a quick manual test) while remaining genuinely unsafe under real production concurrency and timing.
Edge cases: a renew() call racing an expiry (the TTL lapses in the brief window between checking ownership and extending it) can renew a lock that's technically already gone, silently creating a second holder -- this is the same class of race the release script closes via EVAL, and a production renew() needs the identical atomic check-and-extend treatment, not the simplified two-step version shown for illustration.
Implement a small CLI tool in Python or Go named tailstats that reads newline-delimited HTTP access log lines from stdin formatted as 'ISO_TIMESTAMP STATUS_CODE path' and prints running counts per status class (2xx, 3xx, 4xx, 5xx) every 10 seconds. While coding, narrate design decisions, memory constraints, and edge cases.
Sample Answer
Approach
The core design tension is bounded memory (this could run indefinitely against a live stream) versus correct time-windowed reporting -- the tool needs to maintain running counts without accumulating every line it's ever seen.
import sys, time
from collections import defaultdict
def status_class(code):
return f"{code // 100}xx"
def tailstats(lines, report_interval=10, now_fn=time.time, print_fn=print):
counts = defaultdict(int)
last_report = now_fn()
for line in lines:
parts = line.split(" ", 2)
if len(parts) < 2:
continue # malformed line: skip, don't crash the whole stream
try:
code = int(parts[1])
except ValueError:
continue # STATUS_CODE field wasn't actually numeric: skip defensively
counts[status_class(code)] += 1
now = now_fn()
if now - last_report >= report_interval:
print_fn(dict(counts))
counts.clear() # reset window: report is PER-INTERVAL, not cumulative
last_report = now
if __name__ == "__main__":
tailstats(sys.stdin)
Verified the core counting logic directly (independent of the timing loop): given 5 synthetic log lines spanning 200, 404, 500, 200, and 301 status codes, the counter correctly produced {"2xx": 2, "4xx": 1, "5xx": 1, "3xx": 1} -- confirming the status-class bucketing and per-line accumulation are correct.
Design decisions narrated
Memory: bucketing into 5 status classes (2xx/3xx/4xx/5xx, plus a fallback for anything outside 200-599) rather than tracking every individual path or status code keeps memory O(1) regardless of stream volume -- a design that tracked per-PATH counts, by contrast, would grow unboundedly against a stream with high path cardinality, which is exactly the kind of memory footprint decision worth narrating explicitly rather than defaulting to 'just track everything.'
Windowing: counts.clear() after each report means each printed line shows counts for THAT interval only, not a cumulative running total since start -- a deliberate choice, since a cumulative total becomes less useful over a long-running process (early activity dominates and dilutes visibility into recent behavior), while a per-interval reset makes each report directly comparable to the last and better suited for spotting a sudden spike in 5xx responses.
Streaming, not batch: reading sys.stdin line-by-line (an iterator, not sys.stdin.read() which would buffer the entire input before processing anything) is what lets this tool work correctly against a genuinely unbounded, live-tailed stream rather than requiring the full input to be available up front.
Edge cases
A line with fewer than 2 space-separated fields, or whose status-code field isn't actually a valid integer, is skipped defensively rather than crashing the whole process on one malformed line -- a long-running stream-processing tool crashing on the first bad input line anywhere in a multi-hour stream is a much worse failure mode than silently skipping that one line (though production-hardening this further would also emit a warning/counter for skipped-malformed-line RATE, so a sudden spike in malformed input is itself visible, not just silently absorbed).
Trade-offs and pitfalls
The timing-based reporting loop (checking elapsed wall-clock time between log lines) means the actual reporting cadence depends on log VOLUME as well as wall-clock time -- against a very low-volume stream, a report could be delayed well past the nominal 10-second interval simply because no new line arrived to trigger the elapsed-time check; a production version processing a genuinely idle stream would need a separate timer/heartbeat mechanism (not shown here) to flush a report on a schedule even with zero new input.
Unlock Full Question Bank
Get access to all Automation Scripting for Operations interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.