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.
A plan in CI suddenly wants to recreate live resources after a colleague applied changes from their workstation. What does that tell you about the state, and how would you debug it before touching production?
Sample Answer
A plan that suddenly wants to recreate live resources usually means the state and reality are out of sync, or CI is looking at a different state than the workstation did. State is Terraform’s map of managed objects, so if it is stale or mismatched, Terraform may think a resource disappeared and needs to be rebuilt.
What I would check first
- Same backend, workspace, account, and region in CI and locally
- Whether the colleague applied to the same state file
- Whether resource addresses changed because of
count,for_each, or renamed modules - Whether the provider is now seeing drift in an immutable field
Debug path
I would run a refresh-only plan, inspect the current state, and compare it with the real cloud resources before touching production. If the issue is just an address change, I would prefer a moved block or state mv over deleting anything.
Example
If CI wants to recreate aws_instance.app[0] after a workstation apply, that may mean the list order changed or CI is pointing at old state. I would stop, find the mismatch, then fix state or code first.
For a high-criticality service, would you rather have Terraform automatically reconcile drift back to the declared state, or just detect it and alert a human? Why, and what could go wrong with the automatic approach?
Sample Answer
Direct answer
For a high-criticality service, prefer detect-and-alert as the default, with fully automatic reconciliation reserved for a narrow, pre-classified set of low-risk resources. The reasoning is that automatic apply removes the human check at exactly the moment something unexpected is happening in production, which is precisely when you want a person to look before more automated changes land on top of an already-surprising state.
Structured elaboration
Why detect-and-alert by default
- Automatic reconciliation applied blindly can hide symptoms or apply the wrong fix if drift is actually a side effect of an incident in progress, rather than an accidental console change.
- A noisy or slightly wrong detector, alerting a human, gets caught in triage; the same false positive feeding an automatic reconciler just re-applies an unwanted change on a loop.
- Auto-reconciliation can fight transient, legitimate state, for example an autoscaler adjusting instance count, creating thrash if the reconciler and the autoscaler disagree about what "correct" looks like.
- Every automated fix on a high-criticality resource needs an audit trail for compliance and postmortems; an approval step naturally creates that record, an automatic fix needs to be logged just as rigorously to match it.
Classifying what is actually safe to auto-remediate
Not every resource on a critical service carries the same risk if changed automatically. Tag drift, a naming convention violation, or a non-load-bearing config value are reasonable candidates for rate-limited auto-fix. Network configuration, IAM permissions, database instance class, and anything else that can directly cause an outage or a security gap belong in the alert-and-approve bucket, regardless of how "critical" the overall service is.
Detecting drift early is a separate dial from automating the fix
Catching drift before it becomes a problem is mostly a detection-cadence question, not an automation question. How often you scan for drift (a scheduled, plan-only run every few hours instead of once a day, or a webhook-triggered check on any out-of-band API call) determines how large a drift window can accumulate before anyone notices, independent of whether the fix itself is automatic. You can turn up detection frequency to shrink that window and reduce blast radius without ever turning on auto-apply for anything.
Worked example
Classifying a small set of drifted resources on a critical service: a missing Environment tag on an EC2 instance is safe to auto-fix on a rate-limited schedule, since it has no effect on traffic or security. A security group rule that now allows a wider CIDR than declared goes straight to alert-and-approve, since reverting it automatically without knowing why it changed could re-open or re-close access mid-incident. An RDS instance class that drifted smaller than declared (someone downsized it during a cost review, undocumented) also goes to alert-and-approve, since automatically resizing it back up touches a stateful resource and could trigger an unplanned failover.
Trade-offs & pitfalls
- What can go wrong with the automatic approach specifically: if a drift is actually someone's intentional mitigation applied by hand during an active incident, for example bumping an instance size to relieve pressure, a reconciler that "fixes" it back to the declared value reverts the mitigation mid-incident, potentially making things worse right when a human just made a deliberate, informed trade-off.
- Rate-limiting auto-remediation avoids one kind of thrash (fighting another automated system) but does not by itself prevent a bad detector from repeatedly flagging the same false positive; the detector's own accuracy needs monitoring, not just the remediation action's blast radius.
- Treating "high-criticality service" as a single label rather than classifying per-resource risk within that service is itself a common mistake; it leads teams to either auto-remediate too much (because the service is "important, keep it consistent") or alert-fatigue everyone (because nothing is trusted to auto-fix, even harmless drift).
What is configuration drift, and how would you actually detect it, say for a small team versus a large enterprise with hundreds of accounts?
Sample Answer
Configuration drift is when the real state of a resource no longer matches what's declared in code, because someone or something changed it outside the normal pipeline, a console click, an autoscaler, or a break-glass fix. Left undetected it causes deploys to fail unexpectedly, opens security and compliance gaps, and eventually causes an apply that either silently reverts someone's emergency fix or fails because the tool's assumptions about current state are wrong. How you detect it scales with team size: a small team can get by with terraform plan in CI and an occasional manual look; hundreds of accounts need continuous, provider-native scanning because nobody can watch that many plans by hand.
Detection methods and their operational cost
| Method | How it works | Fits | Operational cost |
|---|---|---|---|
IaC plan/diff in CI (terraform plan -detailed-exitcode, scheduled) | Re-plans against real state, fails or flags on any diff | Small team, one or a few accounts | Low: reuses existing CI, but scanning every account on a schedule gets slow and API-throttled as account count grows |
| Cloud-native config service (AWS Config, Azure Policy, GCP Asset Inventory) | Continuously records resource state and evaluates rules | Large enterprise, many accounts and regions | Higher setup cost, aggregators and rule authoring, but low marginal cost per account once wired |
| Third-party drift scanner | Cross-references live cloud state against Terraform state files | Mid-size, multi-tool estates | Medium: another credentialed tool to operate, but catches resources Terraform doesn't manage too |
Detecting without customer impact, at scale
Detection should always be read-only, plan, describe, and list calls, never anything that touches the resource, so scanning hundreds of accounts never risks the workload it's checking. At enterprise scale that means a central scanning identity with read-only cross-account roles rather than one credential per account to manage, aggregated results in one dashboard, and rate-limited API calls so drift scanning doesn't itself trip service quotas that page someone.
Auto-remediate or alert a human
Not all drift deserves the same response. A tag changed by hand is safe to reconcile automatically; a security group opened to the world, or a change in a hybrid Terraform-and-Ansible environment where Ansible legitimately manages day-2 configuration Terraform doesn't track, should alert a human rather than auto-revert, because auto-remediating could undo a deliberate, valid change made by the other tool. A reasonable default: auto-remediate low-risk, easily-reversible drift; alert and require review for anything security-relevant, stateful, or ambiguous about which tool owns it.
Once drift is found
Confirm it's real first, ruling out a stale cache or a provider-side eventual-consistency blip, identify who or what made the change from audit logs, then decide accept-into-code or revert, and only then act through the normal pipeline rather than another manual edit.
Trade-offs & pitfalls
Scanning more often catches drift sooner but multiplies noisy alerts and API cost; the common failure mode is a team turning off alerting after getting paged for cosmetic drift, which defeats the purpose. Cloud-native config services give the best enterprise-scale coverage but carry their own onboarding cost that a two-person team can't justify, which is exactly why the small-team answer leans on CI plan checks instead.
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.
Before a Terraform or CloudFormation change ever reaches apply, what automated checks would you want running in the pipeline, and at what stage would each one run? Talk through what kind of mistake each check is actually meant to catch.
Sample Answer
Direct answer
Run checks in a layered pipeline ordered from cheapest to most expensive: format and lint first (seconds, no cloud access), then static policy/security scanning against the plan or template (still no cloud access), then anything that actually stands up real resources (integration tests, plan review with real credentials), and finally post-deploy verification against the live environment. Each layer is designed to catch a different class of mistake, and putting the cheap checks first means a typo never has to wait for an expensive real-resource test to fail.
The two fundamentally different kinds of check
Before mapping tools to stages, it's worth naming the split explicitly: some checks are fast, syntax- or policy-level, and need no cloud access at all; others genuinely stand up real (usually short-lived) infrastructure to prove it actually works. Confusing the two, or skipping straight to the expensive kind, is the most common mistake in a pipeline like this.
| Stage | Check | What mistake it catches | Provisions real resources? |
|---|---|---|---|
| Pre-commit / local | terraform fmt, cfn-lint, ansible-lint | Style drift, malformed syntax, obviously invalid template schema | No |
| CI: fast lint | terraform fmt -check, tflint | Provider-specific misuse, deprecated arguments, obvious logic errors | No |
| CI: static policy/security | checkov, cfn_nag, OPA/Sentinel against the plan JSON | Security misconfiguration (public S3 bucket, overly broad IAM), missing required tags, policy violations | No, reads the plan or template, never calls the cloud provider to create anything |
| CI: unit tests | Module output assertions, template rendering tests | Wrong variable defaults, broken output wiring, logic bugs in the module itself | No |
| CI: plan review and gating | terraform plan posted to the PR, human or automated diff review | Unexpected destroy/replace actions before they ever reach a real environment | No, it's a dry run |
| CI: integration tests | Terratest, Molecule against a container or real cloud instance | Whether the resource actually gets created correctly, whether runtime configuration is right, whether the API actually accepts what you declared | Yes, real (usually ephemeral) resources |
| Post-deploy | Smoke tests, health checks against the deployed environment | Whether the deployed service is actually reachable and healthy in this specific environment | Yes, against the live environment |
Worked example: a pipeline definition
jobs:
fmt-and-lint:
steps:
- run: terraform fmt -check -recursive
- run: tflint
policy-scan:
needs: fmt-and-lint
steps:
- run: checkov -d . --framework terraform
plan:
needs: policy-scan
steps:
- run: terraform plan -out=plan.tfplan
- run: terraform show -json plan.tfplan > plan.json
# a script here fails the job if plan.json contains an unreviewed delete/replace
integration-test:
needs: plan
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps:
- run: go test ./test/... -run TestModule -timeout 30m
# this job is the one that actually provisions and tears down real infra
apply:
needs: integration-test
environment: production # requires manual approval
steps:
- run: terraform apply plan.tfplan
The ordering matters: fmt-and-lint and policy-scan run on every commit because they're free and fast; integration-test, which provisions real infrastructure, is scoped to run only on merges to main, not on every push to a feature branch, to bound cost and time.
Trade-offs and pitfalls
- Skipping straight to integration tests (or relying on them to catch what a linter would have caught in seconds) is slow and expensive for no extra safety, put the cheap checks first and let them fail fast.
- Running the real-resource layer on every commit, rather than on merge or nightly, is the single most common way teams accidentally burn cloud spend on a testing pipeline.
- Static policy scanning only catches what it has rules for; it gives false confidence if the rule set isn't kept current with new resource types the team starts using.
- A plan-review gate that only a human reads doesn't scale, encode the "never allow an unreviewed delete on a protected resource" rule as an automated check on the plan JSON, not just a habit.
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.