Infrastructure as Code and Automation Questions
Defining, provisioning, and automating infrastructure programmatically. Covers declarative IaC with Terraform and comparable tools like CloudFormation (resource and provider model, state management and remote backends, module design and reuse, workspaces, drift detection, and safe plan/apply workflows), plus the broader automation discipline: provisioning pipelines, golden-image and machine-image building, scripting glue, self-service platforms, and end-to-end environment stand-up. The authoring, lifecycle, and automation of infrastructure code that reduces manual toil across provisioning workflows.
Design a drift-detection and remediation system for thousands of cloud resources spread across multiple accounts and regions. How would it decide what to auto-fix versus what needs a human to sign off, and how do you keep the whole thing auditable?
Sample Answer
At this scale the system has three jobs: detect drift cheaply across thousands of resources without hammering provider APIs, classify each drift by risk and blast radius so only the genuinely dangerous cases interrupt a human, and record every decision so the whole thing survives an audit. The core design is an event-driven detector backed by a scheduled baseline sweep, feeding a risk classifier that routes low-risk stateless drift to automatic remediation and anything touching stateful or security-sensitive resources to a human approval queue, with every step written to an append-only audit log.
Architecture
flowchart TB
A[Scheduled sweep] --> C[Drift Detector]
B[Change event] --> C
C --> D[Risk + severity classifier]
D --> E{Route}
E -->|low risk, stateless| F[Auto-remediate]
E -->|elevated risk or stateful| G[Approval queue]
G --> H[Human sign-off]
H --> F
F --> I[(Audit log, append only)]
G --> I
D --> J[Page on-call if P1]
Detection: event-driven plus scheduled, not either/or
Pure scheduled scanning, a terraform plan sweep across every workspace on a timer, is simple but doesn't scale cleanly to thousands of resources: at high account and workspace counts it turns either infrequent, drift sits undetected for a day, or API-throttled and slow. Pure event-driven detection, reacting to change events, is fast but has a coverage gap: a missed or delayed event means drift that's never checked. Production designs run both: a fast event-driven path reacting within minutes for anything change-event-visible, and a slower scheduled full sweep as the backstop that catches whatever the event path missed. This also avoids two reconciling systems fighting each other: only one component, the reconciler, is allowed to write remediation actions; the event path and the scheduled sweep both just feed the same detector, neither remediates independently.
Noisy false positives at scale
At hundreds of workspaces, naive diffing surfaces a lot of drift that isn't actionable: provider-computed fields that change on their own, timestamps, autoscaling-driven instance counts. Filter these before they reach a human, with an allowlist of expected-to-drift attributes per resource type, and a minimum-repeat threshold that only alerts if the same drift is still present on the next sweep, to filter out transient blips.
Risk classification and severity
| Tier | Example | Action |
|---|---|---|
| P1, security-relevant | Security group opened to 0.0.0.0/0, IAM policy widened | Auto-remediate immediately and page on-call |
| P2, operationally risky | Instance type changed, autoscaling config drifted | Queue for human approval within the normal work day |
| P3, cosmetic | Tag or description changed | Log only, batch into a periodic digest, no page |
Severity is a function of resource type, the specific attribute that changed, and a criticality tag on the resource, not just "something changed."
Stateless vs stateful: different safety gates
A fleet of stateless web servers behind an autoscaler is safe to auto-remediate destructively: replace the drifted instance from the golden image or force an autoscaling group refresh, because no unique data lives on the instance. A stateful service like a database is a different problem: never auto-remediate by destroy-and-recreate, because that risks data loss. For stateful resources the system should default to detect-and-import, bringing the drifted-but-legitimate state under management via terraform import after human review, rather than detect-and-revert, and any destructive action on a stateful resource requires an explicit human approval step regardless of the computed risk score.
When two tools own the same hosts
In a hybrid shop where Terraform provisions infrastructure and Ansible owns day-2 configuration, a naive drift detector misreads Ansible's legitimate changes as unauthorized drift and tries to auto-remediate over them. The fix is an explicit ownership boundary tracked per attribute, not per resource: Terraform's desired state wins for anything it provisions (instance type, security group membership, subnet placement), Ansible's desired state wins for anything it configures (installed packages, running services, config files), and the risk classifier is fed this boundary so it never routes an Ansible-owned attribute into the Terraform remediation path or vice versa. This boundary is a prerequisite for automated remediation, not an optimization: without it the two tools will eventually fight over the same attribute, each reverting the other's legitimate change. Detection wiring differs per tool accordingly: Terraform drift comes from terraform plan -detailed-exitcode (exit code 2 means drift) run against the provisioning-owned attributes, while Ansible drift comes from ansible-playbook --check --diff runs against the configuration-owned attributes, on separate schedules against separate attribute sets. If a resource genuinely needs to move ownership from one tool to the other, that's a deliberate migration with human sign-off, never something the drift system decides on its own.
Multi-cloud prioritization
Across multiple cloud providers, raw discovery order, whichever provider's scanner happened to run first, is a bad prioritization signal. The remediation queue should be ordered by business-criticality tag and blast radius, how many downstream services depend on this resource, rather than which cloud reported it first, so a P1-equivalent issue in a smaller, less-instrumented cloud doesn't sit behind a backlog of P3 issues from the cloud with the most resources.
Preventing remediation loops
If an external system keeps re-modifying a resource the reconciler keeps "fixing", that's a loop. Guard it with a repeat-offender counter per resource: after a small number of auto-remediations of the same resource within a time window, stop auto-remediating and flip it to the human-approval queue with the history attached, instead of fighting the external system forever.
Audit trail
Every stage, detected, classified, routed, remediated or approved, applied, writes an immutable record with pre and post state, and who or what triggered the action, so any change can be traced end to end and replayed for a compliance review.
Trade-offs & pitfalls
Auto-remediation is the highest-leverage part of the system and the highest-risk: too aggressive and it fights legitimate operator changes or destroys data; too conservative and the human queue drowns in low-value approvals until people stop reading it. The repeat-offender loop guard and the stateless/stateful split keep the aggressive side safe; severity tiering and noise filtering keep the human queue usable.
You're advising a team moving from long-lived servers to baked images. What are the trade-offs against staying with configuration management on mutable servers, especially around patching, hotfixes, debugging, and deployment speed?
Sample Answer
Direct answer
Recommend immutable, baked images (images built once with everything preinstalled, then deployed as-is rather than configured after boot) as the default for anything at fleet scale, because they buy reproducibility and safe rollback; keep configuration management for runtime-only concerns (secrets injection, feature toggles, small dynamic config) and as a deliberate bridge during migration, not as the long-term patching strategy. The trade-offs mostly show up in four places: how patches ship, how urgent hotfixes get applied, how debugging works, and how deployment speed scales with fleet size. That default flips for a stateful service, which needs its own answer below.
Structured elaboration
Comparison
| Concern | Baked images (immutable) | Configuration management (mutable) |
|---|---|---|
| Patching | Rebuild the image with the patch, redeploy via rolling replace; consistent across the whole fleet, easy to roll back by pointing at the previous image | Apply in place with Ansible or Chef across the fleet; fast for a handful of hosts, but risks partial application and drift if a run fails partway |
| Hotfixes | Requires a rebuild-and-replace cycle; slower to first fix, but the fix is guaranteed to be in every future image, not just the running instances | Can be applied immediately to running hosts; faster time to fix, but the fix has to be separately folded back into the source of truth or it silently disappears on the next rebuild |
| Debugging | The exact environment is reproducible from the image ID and version, so "what is actually running" is never in doubt; live debugging still needs logging and tracing rather than SSH-and-poke | Easy to SSH in and iterate directly on a running host, which can be faster in the moment, but every such change is an undocumented, untracked snowflake until someone remembers to encode it |
| Deployment speed at scale | Slower for a single one-off change (build, test, replace), faster in aggregate as fleet size grows, because every instance is guaranteed identical and rollouts are automatable | Faster for a handful of hosts, but velocity degrades as fleet size grows because keeping every host consistent becomes a manual, error-prone effort |
When each makes sense
- Prefer immutable images for stateless, autoscaled fleets: the automation investment (image pipeline, CI, registry) pays for itself once more than a handful of instances are being managed.
- Keep configuration management for genuinely dynamic, runtime concerns: injecting secrets at boot, toggling a feature flag, or configuring something that legitimately needs to change without a full rebuild.
- During a migration specifically, a hybrid approach is normal and reasonable: bake the OS and runtime into the image, and use lightweight, idempotent configuration at boot for the parts that still need to vary per environment. That is not indecision, it is how most teams actually get from mutable to immutable without a big-bang cutover.
The stateful-service case
For a stateful service, for example a database node or a broker holding local queue data on disk, naive image-replacement breaks the pattern above. Terminating an old instance and swapping in a fresh one from a new image throws away whatever state lived only on that instance; the deregister-drain-terminate flow that makes stateless replacement safe does not, by itself, move that state anywhere. There is also a handoff problem a stateless fleet does not have: something has to own transferring or re-syncing the state (or explicitly failing it over) before the old instance goes away, not just draining its connections.
Two realistic patterns:
- Separate state from compute where possible. Move the data itself onto something outside the instance's lifecycle, an external volume that reattaches to the new instance, or a managed data store, so the compute layer becomes stateless again and can be image-replaced exactly like the fleet case above. This is the preferred pattern whenever the workload allows it, because it lets the stateful service inherit the same rollback and testing story as everything else.
- In-place with strict drift controls when separation is not possible. If state genuinely has to live on the box, or the migration to external state has not happened yet, stay with configuration management for that host, but treat convergence checks as a required gate after every run rather than an optional audit, since a failed run on a stateful host is far more costly to miss than on a stateless one.
The same three axes from the comparison above still drive the decision, but they cut differently here:
- Rollback complexity: rolling back a baked image is instant for stateless compute, but rolling back a stateful host means rolling back its data too, not just its binaries; an image-based rollback plan for a stateful service has to include a data restore or failover step, not just a launch-template revert.
- Configuration drift: drift is more dangerous to tolerate on a stateful host, because a missed convergence run there does not just leave a config mismatch, it can leave that host holding data no other instance has, which makes it unsafe to simply terminate and replace.
- Testing requirements: testing a stateful change means testing against a realistic copy of the data (a snapshot or a replica), not just a fresh boot; a stateless image can be smoke-tested cold, a stateful one usually cannot.
Worked example
A team migrating a fleet of 40 application servers from Chef-managed mutable hosts to baked AMIs, mid-migration: 15 servers have already moved to immutable images, 25 are still Chef-managed.
- An OS-level CVE needs patching across all 40. For the 15 immutable servers: rebuild the AMI, run it through the standard test and canary gates, and replace those instances via a rolling instance refresh, with no manual steps on any host.
- For the 25 still-mutable servers: run the existing Chef cookbook update across them directly, which is faster to start for that subset but needs a fleet-wide Chef run to confirm every one of the 25 actually converged, since a failed run on any single host leaves it unpatched and undetected until the next audit.
- This is exactly the operational cost mutable configuration carries at scale: the same patch requires two different verification strategies depending on which half of the fleet a given host is in, and the mutable half needs an explicit convergence check the immutable half gets for free from "the image ID changed."
Trade-offs & pitfalls
- The most common mistake is presenting this as all or nothing. A hybrid, migration-aware answer is the stronger answer; a purist "always immutable" answer that ignores legitimate runtime-config needs is not.
- Debugging discipline has to change with immutability: if engineers keep SSHing into production and hand-patching "just this once," the fleet quietly becomes as inconsistent as the mutable model it was supposed to replace, just with extra image-pipeline overhead on top.
- Do not understate the upfront cost of the image pipeline (CI, registry, automated tests, rolling-replace tooling); it is real engineering investment that has to be justified against the ongoing toil of drift remediation and manual patch campaigns it replaces.
- For a stateful service, do not default to "just bake it anyway": image-replacement that ignores where the state lives is not a safer version of the stateless pattern, it is a data-loss risk wearing the same rollout choreography.
Even if nobody hardcodes a secret anywhere in your Terraform source, how can a secret still end up sitting in plaintext somewhere you didn't expect, and what would you put in place to protect against that?
Sample Answer
Direct answer
A totally clean .tf source doesn't guarantee no plaintext secrets, because Terraform itself creates two more places a value can end up: the state file, which stores full resource attributes (including provider-generated secrets like an RDS master password) in plaintext by default regardless of anything in source, and any tooling built around Terraform's own output, like a CI job that posts a plan summary, which can print exactly the values you thought were protected. Defending against this means treating state as sensitive data (encrypt it, restrict who can read it) and understanding precisely what the sensitive flag does and does not cover, rather than assuming "no secrets in the .tf files" is the whole job.
Where it leaks and what to do about it
The state file itself
Whenever Terraform reads back a resource's real attributes, an auto-generated RDS password, a private key from a tls_private_key resource, an API key a provider returns, those values land in terraform.tfstate as plaintext JSON, independent of whether any .tf file ever mentions a secret. Mitigation: server-side encryption on the backend (S3 with SSE-KMS, GCS with CMEK), IAM/access policy that limits who can read the state object, and state locking so nobody's casually pulling and re-uploading a stray copy.
What sensitive = true actually redacts
- What it DOES do: masks the value in the interactive plan/apply diff, in
terraform output(prints<sensitive>instead of the value), and in most default log output. - What it does NOT do: it does not encrypt or redact the value inside the state file itself, the raw state, and
terraform show -json, still contain the real value. It's a display-layer guard, not a storage-layer or access-control guard.
The PR-plan-summary-bot leak
A common pattern: a CI job runs terraform plan -out=tfplan, then terraform show -json tfplan, and a script turns that JSON into a human-readable comment on the pull request. If that script naively reads the plan's after (or before) attribute values to build the summary, a value marked sensitive in source shows up in plain text in a PR comment, a location that's usually far more widely readable (the whole engineering org, sometimes an external contractor) than the CI system's own console output. The same risk shows up in the CI job's own logs if the job runs with verbose/debug logging (for example TF_LOG=trace) that dumps provider request/response bodies. Mitigation: any tool consuming terraform show -json output must read the plan's after_sensitive / before_sensitive markers and redact those keys before rendering anything to a comment or log, rather than assuming the CLI's own masking has already been applied to the JSON, it has not.
Worked example
Suppose an aws_db_instance uses manage_master_user_password = true so AWS/Terraform manages a generated password, and a separate random_password output is used elsewhere:
output "app_db_password" {
value = random_password.app_db.result
sensitive = true
}
Running terraform output app_db_password prints <sensitive> in the terminal, the protection working as designed. But terraform show -json terraform.tfstate (or simply opening the state file if it's stored unencrypted) prints the resource's values block including the real password string, because state serialization does not consult the sensitive attribute at all, that flag only affects the CLI/UI rendering layer, exactly as described above.
Trade-offs and pitfalls
- Treating
sensitive = trueas "the secret is now safe" is the single most common mistake, it only changes what's printed to a screen, not what's stored. - Encrypting the backend protects data at rest but not against a legitimately-authorized reader with over-broad IAM simply opening the state.
- Building any custom tooling on top of
terraform show -json(dashboards, PR bots, drift reporters) reintroduces the exact leak the CLI's own masking prevents, unless that tooling explicitly re-implements redaction using the sensitivity markers in the JSON. - The most robust long-term fix is minimizing what actually needs to be provider-generated and stored in state at all, preferring external secret managers with dynamic, short-lived credentials over resources that bake a static secret into Terraform's own bookkeeping.
A client runs workloads both on-premises and in the cloud, and you're deciding between imperative scripting and declarative IaC to automate both. Walk through the trade-offs, including idempotency, debugging and observability, vendor lock-in, and team skills, and what you'd actually recommend.
Sample Answer
Direct answer
For a client running workloads both on-premises and in the cloud, default to declarative IaC (Terraform, OpenTofu, an open source fork of Terraform, or CloudFormation where the target is AWS-only) for anything that represents steady-state infrastructure, because idempotency and drift visibility come largely built in, and reserve imperative scripting for the parts declarative tools genuinely do not express well: multi-step conditional workflows, human approval gates, and one-off data migrations. The two are not mutually exclusive: compose declarative modules for the actual infrastructure state, and wrap them with an imperative pipeline or workflow engine for sequencing across the hybrid environment.
Structured elaboration
Comparing the two approaches on the axes that matter here
| Axis | Declarative (Terraform/OpenTofu, CloudFormation) | Imperative (bash/SDK scripts, ad hoc automation) |
|---|---|---|
| Idempotency | Native: the engine computes a diff against desired state and only changes what needs to change | Not automatic; every script has to be written to check-before-act, and that discipline regresses easily |
| Debugging and observability | A plan shows the intended change before it happens, and the state file is inspectable, but provider-level convergence failures can be opaque | Step-by-step logs make root cause easy to trace, but there is no single artifact you can inspect ahead of time to see everything that will change |
| Vendor lock-in | Provider abstractions can be fairly portable across clouds, but the tool's own licensing and ecosystem is a separate axis of lock-in | Direct SDK/CLI calls are inherently provider-specific unless someone deliberately abstracts them, but there is no tooling-level lock-in |
| Team skills | Lower barrier for infrastructure-focused operators; requires discipline in module design and state hygiene | Needs software-engineering habits, idempotency, retries, testing, that not every operations team has built up |
Vendor lock-in has two separate axes, and one of them changed recently
It is worth separating provider lock-in (which cloud or on-prem APIs your modules target) from tooling lock-in (which organization controls the engine and its licensing terms). HashiCorp moved Terraform off its original open-source MPL license onto the Business Source License in 2023, which is what triggered the OpenTofu fork, maintained under the Linux Foundation as an open-source, largely drop-in alternative. For a hybrid client weighing lock-in, that is a tooling-lock-in consideration distinct from whether their modules are portable across on-prem and cloud providers.
Where the two compose
Use declarative modules as the primary pattern for provisioning and ongoing stateful resources on both on-prem and cloud sides, since that preserves idempotency and auditability everywhere. Wrap the orchestration of a hybrid rollout, sequencing, approvals, cross-environment coordination, in a pipeline (CI/CD) or workflow engine that calls into those declarative modules rather than reimplementing infrastructure logic imperatively.
Worked example
Say the client needs to migrate 40 VMs off on-prem VMware, with some staying on-prem and the rest moving to a cloud provider. The steady-state definitions for both the vSphere-hosted and cloud-hosted VMs live in parameterized Terraform/OpenTofu modules, one per provider, sharing a common interface (name, size, network, tags). The migration sequence itself, drain traffic from a VM, provision its cloud replacement, validate health checks, cut over, decommission the on-prem VM, is not something the declarative modules express well as a single unit, so it runs as a pipeline stage (GitHub Actions or a workflow engine) that calls terraform apply for each phase with an explicit manual approval gate between "provision replacement" and "decommission original," since the decommission step is destructive and on-prem hardware is not trivially recoverable.
Trade-offs & pitfalls
- Embedding imperative logic inside a declarative tool's own provisioners (
local-exec/remote-exec) is a common anti-pattern: it breaks the engine's ability to reason about and safely re-run the plan, since the side effect of a shell command is invisible to the state model. - The opposite mistake also happens: standing up a full workflow engine for orchestration that a plain module dependency graph could already express adds operational surface (another system to run, secure, and understand) with no real benefit.
- Recommending OpenTofu purely on cost or philosophy without checking provider/module compatibility for the client's specific stack can introduce its own migration risk; the fork is close to drop-in but is not automatically identical for every provider version in use.
What is Terraform state, and why does Terraform need to keep track of it at all? What would actually break if it didn't exist?
Sample Answer
Direct answer
Terraform state is the record, a JSON file, local or (far more commonly) in a remote backend, of the mapping from every resource block in your configuration to the real-world object it created, plus that object's last-known attribute values. It exists because provider API calls alone can't tell Terraform "this resource address already corresponds to that cloud object" or "here's what its attributes were the last time we looked." State is what lets plan compute an actual diff instead of guessing, and what lets apply update or destroy the correct object instead of creating a duplicate.
What's actually inside the state file
- Resource mapping: resource address to real cloud resource ID, for example
aws_instance.webtoi-0123456789. - Attributes and metadata: the last-known values of every attribute, including computed ones the provider filled in, plus timestamps.
- Dependency graph metadata: what depends on what, and which module each resource belongs to.
- Outputs, and any values a data source resolved.
- Terraform version and a serial number, used to detect concurrent state modifications.
What state makes possible
- Idempotent plan/apply: comparing desired config against last-known state, rather than re-describing everything from the provider on every run, lets
plancompute a targeted diff and lets repeated applies against unchanged config produce a no-op. - Resource targeting (
-target): Terraform resolves a targeted address using the mapping in state; without that mapping there's nothing to reliably point-targetat. terraform import: writes an existing resource's real ID into state under a chosen address, which is exactly what lets Terraform manage a resource it didn't originally create.
Worked example: your config declares
resource "aws_instance" "web" {
ami = "ami-0123456789"
instance_type = "t3.micro"
}
After apply, state records aws_instance.web -> i-0abc123... plus every attribute AWS returned. Change instance_type to t3.small and run plan again: Terraform reads the last-known t3.micro value out of state (it doesn't need to re-describe the instance from AWS to know the old value), compares it to the new config's t3.small, and shows exactly ~ instance_type = "t3.micro" -> "t3.small" as an in-place update, a diff it could not compute correctly without a stored last-known value to compare against.
What would actually break without it
- No diffing: every
applywould have to either blindly re-create everything (duplicate resources on every run) or re-describe every resource from the provider API on every operation, and many attributes (like a write-only password field) can't be losslessly reconstructed that way even if you tried. - No safe in-place updates: Terraform wouldn't know that a config change should modify
i-0abc123in place rather than create a new instance, since there's no persisted mapping from config address to that specific real object. - No dependency-aware destroy ordering: the stored dependency graph is what lets
destroytear things down in reverse-dependency order, and what lets Terraform correctly destroy a resource that's since been removed from config entirely, the current config's graph alone has no idea that resource ever existed. - No detection of external drift: without a last-known snapshot to diff against, Terraform can't distinguish "this attribute changed outside of Terraform" from "this attribute has always had this value."
Trade-offs and pitfalls
State is also a common source of operational pain on its own: when it goes stale (drifts from what's actually deployed) or gets corrupted (truncated, partially written from an interrupted apply, or hand-edited), plan and apply stop being trustworthy. Recovering from that is its own topic rather than a footnote here, but the short version is diagnosing against a known-good, versioned backup of the state object and repairing with terraform state subcommands (mv, rm, import) rather than hand-editing the JSON directly.
Unlock Full Question Bank
Get access to all Infrastructure as Code and Automation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.