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.
Terragrunt, Terraform Cloud workspaces, or composing plain Terraform modules: how would you choose between them for orchestrating a set of layered deployments, and what does each cost you in maintainability and onboarding?
Sample Answer
Direct answer
Choose based on where you want the dependency graph and orchestration logic to actually live. Terragrunt fits when you want an explicit, code-visible DAG across layered live environments and are fine with an extra tool wrapping Terraform. Terraform Cloud (or HCP Terraform) workspaces fit when you want managed runs and policy-as-code with minimal local tooling, and are fine coordinating cross-workspace dependencies through remote state lookups or run triggers (a Terraform Cloud setting that auto-starts a run in one workspace after another workspace applies) instead of a first-class dependency primitive. Composing plain Terraform modules with your own CI orchestration fits when you want to stay dependency-free on tooling and are willing to hand-write the sequencing logic yourself.
Structured elaboration
Comparing the three on the axes that matter for onboarding a team
| Approach | Maintainability | Coupling between layers | Dependency management | Onboarding cost |
|---|---|---|---|---|
| Terragrunt | High if DRY patterns (include/locals) are used deliberately; can get hard to reason about if overused | Explicit, layer-by-layer directories make environments visible; moderate coupling via remote-state references | Native dependencies/dependency blocks express a real DAG and fetch remote state automatically | New hires need to learn Terragrunt's own config and CLI on top of Terraform |
| Terraform Cloud workspaces | Good; centralizes runs and policy (Sentinel), configs per workspace stay simpler | Workspaces can be loosely coupled, but cross-workspace dependencies need remote state or run triggers, adding coordination overhead | No first-class DAG primitive; relies on workspace variables, run triggers, or terraform_remote_state | Generally easier; VCS integration and a UI reduce local tooling needs |
| Plain composed modules | Portable, testable modules; the root/orchestration layer can get repetitive without its own tooling | Low-level modules stay loosely coupled by design; the root modules can become tightly coupled if not deliberately structured | No orchestration primitive at all; the DAG has to be designed and enforced in CI/CD scripting | Shallow learning curve since it is just Terraform, but the operational sequencing pattern has to be documented, it is not enforced by any tool |
What each one actually costs you
- Terragrunt costs you a second tool in the pipeline and a second thing to debug when something in the DAG resolution goes wrong, in exchange for that DAG being explicit and enforced.
- Terraform Cloud workspaces cost you a dependency on that specific platform's run model and, for cross-workspace sequencing, a discipline problem: nothing stops someone from adding a dependency that only lives in a run trigger nobody remembers configuring.
- Plain modules cost you the least in tooling but the most in process discipline: the correct apply order across layers lives in a README or a CI YAML file, not in anything Terraform itself understands, so it is only as reliable as your team's documentation habits.
Worked example
Take a layered deployment: a network layer (VPC, subnets), a shared-services layer (a database, a message queue) that reads the network layer's outputs, and an application layer that reads the shared-services layer's outputs. With Terragrunt, the app layer's terragrunt.hcl declares a dependency "shared_services" { config_path = "../shared-services" } block, and running terragrunt apply from the app directory automatically fetches the shared-services layer's outputs and applies in the right order. With Terraform Cloud workspaces, the shared-services workspace would have a run trigger configured to notify the app workspace's workspace on a successful apply, or the app workspace's .tf would read the shared-services state via terraform_remote_state pointed at that workspace. With plain composed modules, the app layer's root module also uses a terraform_remote_state data source pointed at the shared-services layer's backend, but the actual apply order across the three layers (network, then shared-services, then app) is enforced entirely by the CI pipeline's stage ordering, not by anything Terraform itself checks.
Trade-offs & pitfalls
- Terragrunt's DRY features (
include,locals, generated blocks) can turn into configuration indirection that is hard to trace when something is wrong; a new team member debugging a plan may need to read three files to find where a value actually came from. - Terraform Cloud's cross-workspace coupling via run triggers is easy to lose track of over time; a workspace can silently depend on another one with no obvious signal in the workspace itself that the dependency exists.
- Plain modules risk the opposite failure: root configurations for different environments drift apart over time (someone adds a resource to staging's root config and forgets prod's) because no tool is enforcing that they stay structurally in sync, only convention does.
Terraform doesn't give you an automatic transactional rollback if an apply goes wrong. What patterns do you rely on instead to safely walk back an infrastructure change, and when is automated rollback the right call versus needing a human to reconcile things by hand?
Sample Answer
Direct answer
Terraform has no built-in transactional rollback because it applies resources one at a time in dependency order, not as a single atomic unit, so "rolling back" is really a set of separate patterns you choose between based on blast radius: reapplying a known-good, version-pinned configuration, restoring a snapshotted state file, or targeted, resource-level remediation. Automated rollback is the right call for reversible, idempotent changes with a clear health signal (a stateless service behind an ASG, a container image swap); a human needs to reconcile by hand whenever the change is destructive, touches stateful data, or the exact post-failure state is ambiguous.
Patterns for walking back a change
Versioned modules and state backups
- Pin every module call to a semantic version tag, so "roll back the infrastructure" can mean "redeploy the previous module version" rather than reconstructing a diff by hand.
- Keep state backend versioning on (S3/GCS object versioning) and snapshot state before every apply, tagged with the pipeline run ID and commit.
Partial rollback versus full rollback
- A full rollback (restoring the entire state file to the last-good snapshot) is the blunt instrument: fast, but it can silently undo any other legitimate change another engineer applied in the meantime, since it doesn't know which parts of the diff are the problem.
- A partial rollback (fixing or re-targeting just the resource(s) that actually broke, using
terraform apply -targetsparingly, or hand-correcting one resource's config) is narrower and safer when you know exactly what failed, but requires that you've actually diagnosed the failure first, guessing wrong under a full state restore is less catastrophic than guessing wrong under a targeted one.
Reapplying configuration management state after an infra rollback
If a configuration management tool (Ansible, Chef, Puppet) runs on top of Terraform-provisioned instances, rolling back the Terraform layer alone (say, reverting an instance's AMI or instance type) does not automatically put that instance's OS-level configuration back in sync. The CM tool's last run was against the instance in its post-change form; after an infra rollback you need to rerun the CM playbook or run-list against the rolled-back instance so both layers agree again, otherwise you end up with infra that matches the old Terraform state but application configuration that still reflects the change you just reverted.
Keeping a multi-resource logical change atomic
A single logical change that spans several resources, for example provisioning a new database instance together with the IAM policies that grant an application access to it, needs to stay consistent even if one part fails. Two practical approaches: sequence the change so a partial failure is safe by construction (grant the IAM policy before the database exists, so a database-creation failure just leaves an unused policy rather than a database nothing can reach), or make each piece individually idempotent so re-running the apply after a partial failure converges to the same end state rather than erroring on "already exists."
Worked example
Say an apply plans five resources in this order: a security group, a DB subnet group, an RDS instance, an IAM policy, and an IAM role-policy attachment. The first four create successfully; the fifth fails because the policy ARN referenced in the attachment has a typo. Terraform writes state incrementally as each resource completes, not only at the end of the run, so at the moment of failure, state already correctly records the security group, subnet group, RDS instance, and IAM policy as created; only the role-policy attachment is missing. Running terraform plan again reflects this accurately: it proposes creating only the missing attachment, not recreating the other four, because state already matches reality for those. The fix is to correct the ARN and reapply; nothing about the first four resources needs to be touched or reasoned about again. This is the diagnostic step that has to happen before deciding between "just reapply" (safe here, since the failure was config-only and everything else succeeded) and "restore from snapshot" (which would be the wrong call here, since it would needlessly discard four correctly-created resources).
Trade-offs and pitfalls
- Automated rollback assumes the operation is reversible and idempotent, true for stateless compute and image swaps, false for anything with an irreversible side effect (a dropped database column, deleted data, a webhook already fired to an external system). Forcing an automated revert onto that class of change is how you turn one incident into two.
- A blanket "restore the old state file" full rollback is dangerous in a team setting precisely because it can undo unrelated, legitimate concurrent changes, prefer targeted remediation once you've actually diagnosed which resource is broken, as in the worked example above.
- Forgetting the configuration-management layer after an infra-level rollback is a common miss: the infra looks reverted, but the OS-level config on that instance can silently stay in the post-change state until the CM tool is rerun.
You inherit a production resource, say a VPC or a database, that was created by hand and now needs to come under Terraform management, without downtime and without Terraform trying to recreate it. Walk me through how you'd actually do that.
Sample Answer
Direct answer
Write a resource block of the correct type declaring only the arguments you intend to manage, run terraform import (or a declarative import block) to attach the real resource's ID to that address, then run terraform plan repeatedly, reconciling your HCL against what it reports, until plan shows no diff. Only then does apply touch anything, and by that point it's a no-op. Nothing about the live VPC or database changes during any of this, because import only writes state and plan never mutates anything, so the "without downtime" requirement is really just discipline about not applying until plan is clean.
Structured elaboration
1. Inspect the real resource before writing HCL
Don't write the resource block from memory. Look up the actual current attributes (via the console, CLI, or the provider's data source) so your first draft doesn't propose spurious changes the moment you import.
2. Write the minimal matching resource block
Keep it to the arguments you actually plan to manage going forward; leave out fields you expect the provider to compute (endpoints, generated ARNs) rather than guessing values for them.
resource "aws_db_instance" "example" {
identifier = "my-db-identifier"
# do not add attributes you expect AWS to compute (endpoint, address)
}
3. Import
terraform import aws_db_instance.example my-db-identifier
As of Terraform 1.5+ you can express the same step declaratively with an import block plus terraform plan -generate-config-out=generated.tf, which scaffolds a starting resource block for you instead of hand-writing one, useful when importing many resources at once.
4. Reconcile computed and drifted attributes
Run terraform plan. Anything present in the real resource but missing or different in your HCL shows up as a proposed change. For attributes the provider computes and you don't want Terraform fighting over (an RDS endpoint, a final snapshot identifier), either add the real value explicitly if you want to manage it, or mark it in a lifecycle block so Terraform stops treating drift there as something to fix.
lifecycle {
ignore_changes = [endpoint, address]
}
5. Verify, then only apply if you mean to change something
terraform state show aws_db_instance.example confirms the mapped ID and attributes. Keep iterating on plan until it's clean. If you genuinely want to change a value going forward, that apply is a deliberate, reviewed change, not an accidental side effect of the import.
Nested/child resources aren't imported automatically
A hand-built VPC or database typically has dependent pieces, a DB subnet group, associated security groups, route tables, that each need their own import call. Importing the parent resource doesn't pull its children into management for you.
Worked example
Importing a hand-built RDS instance end to end:
terraform import aws_db_instance.example my-db-identifier
terraform state show aws_db_instance.example
terraform plan
A first plan on a genuinely hand-built instance will usually show a handful of proposed changes on computed fields like endpoint, address, and tags_all, since those were never in your HCL to begin with. You add ignore_changes for the ones you don't want to manage and explicit values for the ones you do, then re-run plan until it's a clean no-op, which is your confirmation that apply is now safe.
Trade-offs & pitfalls
Skipping the "inspect the real resource first" step is the most common way this goes wrong: you import, run plan, and discover it wants to replace the DB instance's engine or storage_type because you guessed a value instead of reading the real one, right after the whole point was to avoid touching it. Always back up state before starting (terraform state pull > backup.tfstate), and where possible rehearse the import against a non-production copy of the resource type first. Bulk-importing dozens of hand-built resources one CLI call at a time doesn't scale, that's what the 1.5+ import block with -generate-config-out is for.
Explain GitOps as a workflow for infrastructure changes: what does the branch, PR, review, merge, automated-apply flow actually look like, and what does having a reconciler constantly watching git buy you over people applying changes by hand?
Sample Answer
Direct answer
GitOps treats the Git repository as the single source of truth for infrastructure: an engineer opens a PR against the IaC (Terraform, CloudFormation, or similar), CI renders a plan and posts it on the PR for review, a human approves and merges, and only then does something apply the change, either a CI job triggered by the merge, or a reconciler that is continuously watching the repo. What a continuously watching reconciler buys you over ad hoc manual applies is that it also converges any out-of-band drift back to what is in git, not just deploy new commits, so git stays true to what is actually running, not just to what someone last remembered to push.
Structured elaboration
The flow
- Developer creates a branch with the IaC change and opens a PR.
- CI runs a plan (for example
terraform plan) and posts the diff on the PR, along with lint, static checks, and any policy gates. - The team reviews the plan output, not just the code diff, since that is what will actually happen to live infrastructure.
- On approval, the PR merges to the main branch.
- Apply happens one of two ways: a CI job triggered directly by the merge event, or a reconciler that is separately, continuously polling or watching the repo (via webhook) and converging live state toward whatever the latest merged commit declares.
Push-triggered apply versus a continuously watching reconciler
- Push-triggered: an apply only runs in response to a merge event. Nothing happens between merges, so if the live environment drifts out of band (someone changes something through the console), nothing corrects it until the next merge happens to touch that resource.
- Continuously watching reconciler: it does not just react to new commits, it repeatedly compares live state to the declared state and re-converges even when nothing new has merged, which is what catches and fixes drift, not only new intent.
What this buys you over manual applies
- Git becomes the single, versioned record of every change, who proposed it, who approved it, and what actually got applied, which is a real audit trail instead of tribal memory.
- Reviewed plans catch mistakes before they touch production, instead of relying on whoever is running
applyfrom their laptop to notice something is off. - No one needs standing, long-lived cloud credentials on a local machine; only the pipeline or reconciler's service identity needs apply-level access.
Worked example
Say the change is adding a lifecycle rule to an existing S3 bucket to expire objects after 90 days. The engineer edits the bucket module, opens a PR, and CI's plan output shows exactly one resource changing in place, the lifecycle configuration, zero creates, zero destroys. A teammate reviews that plan (not just the HCL diff) and approves. On merge, either the CI apply job runs terraform apply against that one change, or, if the team uses a reconciler pattern instead, the reconciler notices the new commit on its next poll or webhook trigger and converges the bucket to match. If someone had manually added a different lifecycle rule through the console the week before, a reconciler's next pass would have already flagged or reverted that drift independently of this PR; a push-only pipeline would not have caught it until some unrelated change happened to touch that same bucket.
Trade-offs & pitfalls
- Secrets management: nothing sensitive should live in the git-tracked IaC itself. The reconciler still needs a way to pull secrets from a vault or secrets manager at apply time, referencing an ARN or path rather than a value, and the state file itself needs to be treated as sensitive since resolved values can still land there.
- Drift windows between commits: there is always a gap between when something changes out of band and when the reconciler's next poll or webhook fires and corrects it. The length of that window is a direct function of your reconciliation interval, and during it the live state and the declared state genuinely disagree, which matters for anyone debugging an incident in that window.
- Reconciler loops: a reconciler can get stuck reapplying the same "diff" every cycle when a resource attribute is not stably convergent, for example a provider that normalizes a value differently than it stores it, so every pass reports a change and reapplies it. This looks like the reconciler doing its job but wastes API calls and can trip provider rate limits; the fix belongs in the module or resource definition, not in disabling reconciliation.
You need to roll out an infrastructure-level change, say a new machine image or a load balancer/routing config change, with as close to zero downtime as possible. Walk through a blue-green or canary approach: how traffic gets shifted, what health checks and metrics you'd watch before promoting, and what would make you pull the plug and roll back.
Sample Answer
Direct answer
The mechanics are the same regardless of what is being changed: stand up the new version alongside the old one, shift traffic to it gradually (or all at once for blue-green), watch metrics against a defined threshold before promoting further, and have an automated way to shift traffic back if those metrics degrade. What differs by change type is what "the new version" means and which metric actually tells you it is safe, so the mechanics come first below, then how they change for a few different kinds of infrastructure change.
Structured elaboration
Traffic shifting mechanics
- Canary: route a small percentage of traffic to the new version (for example 5%), hold, then ramp (25%, 50%, 100%) with a wait window at each step.
- Blue-green: fully validate the new environment out of band, then cut traffic over in one step (DNS, load balancer listener swap, or weighted routing swap to 100%). Rollback is just swapping back.
What "the new version" and "the signal to watch" are, by change type
| Change type | What actually changes | Primary signal before promoting | What triggers rollback |
|---|---|---|---|
| AMI (Amazon Machine Image) or launch-config replacement | New ASG (Auto Scaling Group, a group of instances that scales automatically) or launch template referencing the new image, registered to the same target group | 5xx rate, app error logs, latency | Error rate or latency breaches threshold for a sustained window |
| Network load balancer or routing config change | Listener rules, target-group weights, or routing paths on the LB itself | Target-group health-check pass rate, connection error rate, latency delta versus baseline | New connection failures or health-check flapping that were not present before |
| Network or security-group rule change | The rule set applied to one canary target group or subnet before the rest of the fleet | Connection-refused and timeout counts, not 5xx, since a bad rule usually blocks the connection before the app ever sees it | Any new connection failures on the canary group that do not exist on the unchanged group |
| ASG instance-type change | Instance type in the launch template, small percentage of the fleet | CPU and memory headroom, p95/p99 latency measured against the SLO's error budget, not just an absolute number | Latency or saturation consumes more of the SLO error budget than the change is worth |
| DB-class change | New instance class, usually validated via a promoted read replica before the primary is touched | Replication lag, query latency, connection-pool saturation | Replication lag or query latency exceeds a defined threshold, or the pool starts queuing |
Stateless versus stateful
For a stateless service, this is close to mechanical: deregister the old instance from the load balancer, let connections drain, terminate it, and the new instance takes over with no coordination needed between old and new.
For a service with state, for example one backed by a database or holding session or connection state, the "new version" cannot simply replace the old one at will:
- Deregistration has to wait for graceful connection draining, not just for the health check to fail, or you drop in-flight work.
- If the state itself is what is changing (the DB-class case above), the new version has to be replication-caught-up before it sees real traffic, and you need a plan for what happens to writes that land during the cutover window.
- The old and new versions may be reading or writing the same underlying data store, so canary steps need to account for that shared state, not just for the request path.
Worked example
A concrete case: shifting 5% of production traffic on an ALB to a target group fronting instances built from a new AMI, before fully cutting over.
resource "aws_lb_target_group" "green" {
name = "app-green"
port = 443
protocol = "HTTPS"
vpc_id = var.vpc_id
health_check {
path = "/health"
healthy_threshold = 3
unhealthy_threshold = 2
timeout = 2
}
}
resource "aws_lb_listener_rule" "canary" {
listener_arn = aws_lb_listener.app.arn
priority = 100
action {
type = "forward"
forward {
target_group {
arn = aws_lb_target_group.green.arn
weight = 5
}
target_group {
arn = aws_lb_target_group.blue.arn
weight = 95
}
}
}
condition {
path_pattern { values = ["/*"] }
}
}
Watch the green target group's 5xx rate and p95 latency for a fixed window (say 15 minutes). If it stays within the same range as blue, bump the weight to 25 and repeat; if 5xx rate or latency breaches the threshold at any step, a second terraform apply (or a CI job wrapping it) sets green's weight back to 0 and blue keeps serving everything.
flowchart TD
A[Provision green environment via Terraform] --> B[Register in target group, run health checks]
B --> C[Shift 5 percent traffic to green]
C --> D{Metrics within SLO?}
D -- Yes --> E[Ramp to 25 percent, then 50 percent]
E --> F{Still within SLO?}
F -- Yes --> G[Shift 100 percent traffic, decommission blue]
F -- No --> H[Roll back: weight to 0 percent, blue keeps serving]
D -- No --> H
Trade-offs & pitfalls
- The biggest mistake is treating every infra change like an app deploy and watching only 5xx rate. A security-group rule change will not show up as a 5xx, it shows up as connections that never complete; a DB-class change will not show up in the app's error rate until replication lag has already gotten bad. Pick the signal that matches what actually breaks for that change type.
- Canary steps for stateful changes need explicit wait-for-caught-up gates, not just a timer; ramping traffic to a replica that has not finished catching up just moves the failure into user-visible latency or stale reads.
- Automating the rollback path, not just the promotion path, is what actually buys "close to zero downtime." If pulling the plug requires someone to remember the right
terraform applyunder pressure, the safety only exists on paper.
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.