Infrastructure as Code and GitOps Questions
Defining and managing infrastructure and delivery state declaratively: provisioning as code (Terraform, CloudFormation, Pulumi, Ansible, Puppet), configuration management, idempotency, drift detection and remediation, and version control for infrastructure definitions, extended by GitOps where git is the source of truth for deployment and infrastructure state. Covers keeping environments consistent, treating config as a first-class versioned artifact, pull-based deployment and continuous reconciliation toward the committed state (ArgoCD, Flux, and similar controllers), Kubernetes manifest and configuration delivery via git, secrets handling for IaC and GitOps pipelines, policy-as-code guardrails (OPA, Sentinel), Terraform state management and locking, and auditable change through version control: branching strategy, pull request review, commit conventions, and code review policy for infrastructure code. Distinct from the CI/CD pipeline design topic, which owns generic pipeline structure and platform-scale release orchestration (build, test, artifact publishing, runner mechanics) and the architectural choice between push-based CI/CD and pull-based GitOps, even when the payload is infrastructure code. Distinct from the safe deployment and rollback strategies topic, which owns deployment-strategy mechanics: canary and blue-green traffic shifting, automated rollback triggered by metrics or SLOs, feature-flag progressive delivery, Kubernetes rollout mechanics (maxSurge, maxUnavailable, health-check gating), and database or schema migration safety as it gates a release, even when the delivery mechanism is GitOps. Distinct from the automation and scripting topic, which owns operational-scripting disciplines (retry and backoff logic, CLI tool design, generic file, checksum, or diff utilities) when the task is not specifically about declarative infrastructure or configuration state. This topic keeps the GitOps reconciliation loop itself, drift detection and remediation, and IaC state and module lifecycle management regardless of which adjacent discipline a question also touches.
Explain how GitOps applies to managing infrastructure. Design a GitOps workflow for an SRE team using a declarative controller (for example Flux or ArgoCD) that ensures environments are reconciled from Git. Include how you handle environment overlays, secret injection, drift reconciliation, and emergency out-of-band changes.
Sample Answer
Direct answer
Applying GitOps to infrastructure means the same declarative, pull-based, continuously-reconciled model already used for Kubernetes applications extends to the INFRASTRUCTURE that hosts them: the desired cluster and environment configuration lives in Git, and a controller (Flux or Argo CD) reconciles the live environment toward it. For an SRE team, the concrete workflow needs four specific mechanisms layered on top of the base reconciliation loop: environment overlays (so one base configuration serves dev/staging/prod without duplication), secret injection (so sensitive values never live in the plain manifests the controller reads), drift reconciliation (so manual out-of-band changes get corrected or at least surfaced), and an explicit, bounded escape hatch for emergency out-of-band changes (so an incident is never blocked on a slower normal Git flow, without abandoning the audit trail entirely).
Structured elaboration
Environment overlays. A base configuration (common to every environment) plus per-environment overlay directories (Kustomize overlays, or per-environment Helm values) captures what genuinely differs: replica counts, resource limits, feature flags, environment-specific hostnames. The controller in each environment's cluster watches ONLY that environment's rendered overlay path, so a change to the base propagates to every environment through their respective overlays, while an environment-specific tweak stays scoped to that one overlay.
Secret injection. An External Secrets Operator instance per cluster (or Sealed-Secrets/SOPS if the team prefers not to take on a live runtime dependency on an external store) resolves secret REFERENCES declared in the overlay into actual Kubernetes Secret objects at apply time, so the Git-committed manifest never contains a plaintext value, only a pointer to where the real value lives.
Drift reconciliation. The controller's normal reconciliation loop detects and, per application-level policy, either auto-heals or alerts on drift (the concrete mechanism is Argo CD's selfHeal setting); for an SRE team specifically, a sensible default is auto-heal for stateless application config and alert-only for anything touching state or currently under active incident response, since an aggressive auto-revert during an incident can undo a legitimate emergency mitigation before anyone has captured it properly.
Emergency out-of-band changes. The explicit escape hatch: a defined, short-lived path (a break-glass role, or a SyncWindow-style pause on auto-heal for a specific application during a declared incident) that lets an on-call engineer make an immediate live change WITHOUT the reconciler immediately reverting it, paired with a HARD requirement that the change gets captured back into Git within a bounded window afterward (the same day, or before the incident is formally closed), so the exception is temporary and auditable rather than a permanent, undocumented divergence from the declared state.
Worked example
A concrete repo and cluster layout for a three-environment SRE-owned fleet:
infra-repo/
base/
deployment.yaml
service.yaml
externalsecret.yaml # references vault path, no plaintext values
overlays/
dev/kustomization.yaml # low replica count, verbose logging
staging/kustomization.yaml # mirrors prod shape at smaller scale
prod/kustomization.yaml # full replica count, SyncWindows configured
Each environment's Argo CD Application object points at its own overlay path. prod's Application additionally sets syncPolicy.automated.selfHeal: false for the specific service currently under active on-call rotation review, with a documented runbook step: "if you make a live emergency change, re-enable selfHeal only after committing the equivalent change to overlays/prod/, within the same incident."
Trade-offs and pitfalls
- Common mistake: designing the emergency escape hatch as "give the on-call engineer standing bypass access." A standing bypass is a permanent weakening of the model's core guarantee; the escape hatch should be TIME-BOXED and auditable (a break-glass grant that expires, or a per-application, per-incident SyncWindow pause), not a quiet permanent exception that erodes Git-as-source-of-truth for whoever happens to hold it.
- Overlay sprawl is a common failure mode as the number of environments grows. Without a convention for what belongs in the base versus what belongs in each overlay, environments drift apart in ways that are hard to track; a periodic review of overlay diffs (are staging and prod diverging in ways nobody intended) keeps the "one base, thin overlays" property real rather than aspirational.
- Secret injection needs its OWN drift/rotation story, not just an initial setup. A secret rotated in the backend should propagate through the same reconciliation mechanism as any other change; treating secrets as a one-time setup task rather than an ongoing reconciled concern leaves rotation as a manual, easy-to-forget side process.
- The emergency-change reconciliation requirement (captured back into Git within a bounded window) is the step teams most often skip once the immediate incident is resolved. Without an explicit follow-up task tracked as part of incident closure (not just a suggestion in a runbook), the live emergency change quietly becomes permanent, undocumented drift.
Define infrastructure-as-code (IaC) drift. Explain how you would detect drift across multiple environments at scale, and describe remediation approaches (reapply, import, destroy/recreate) and guardrails you would put in place to prevent accidental manual changes.
Sample Answer
Direct answer
Infrastructure-as-code (IaC) drift is the gap between the DECLARED state a Terraform/CloudFormation/Ansible configuration specifies and the ACTUAL live state of the resources it manages, opening whenever something changes the real infrastructure through a path OTHER than the normal apply pipeline: a manual console edit, an emergency fix, an out-of-band automated process, or a resource's own natural drift (a certificate auto-renewing, a value the provider itself changes). At scale, across multiple environments, drift needs to be detected on a SCHEDULE (not just discovered accidentally the next time someone happens to run plan), and remediated by one of three genuinely different mechanisms depending on WHAT drifted: reapply (push declared state back over the drift), import (accept the live state and update the declaration to match it), or destroy/recreate (for drift that cannot be reconciled in place).
Structured elaboration
Detecting drift across multiple environments at scale. A scheduled job (not developer-triggered) running terraform plan (with no apply) against EVERY environment's state on a regular cadence, parsing the plan output specifically for changes that are NOT expected (a plan showing "no changes" is healthy; any diff signals drift), and reporting results centrally rather than requiring someone to manually check each environment. At real scale (many workspaces/environments), this needs to run in PARALLEL with rate-limiting and credential-error handling against the underlying cloud APIs, and results need to be aggregated into one dashboard/report rather than scattered across individual CI job logs nobody is checking regularly.
Remediation approach 1, reapply. For drift where the DECLARED state is correct and should simply be restored: run terraform apply to push the declared configuration back over the live drift. Appropriate when the drift was an unauthorized or accidental change and the Git-declared state genuinely represents the intended configuration.
Remediation approach 2, import. For drift where the LIVE state turns out to be the one that should actually be considered correct (a legitimate emergency change that should be formalized, not reverted): update the Terraform CONFIGURATION to match what is actually running, so the next plan shows no diff, rather than fighting a change that was correct. This is the remediation path for "the live state is right, Git needs to catch up," the mirror image of reapply.
Remediation approach 3, destroy and recreate. For drift that cannot be reconciled in EITHER direction cleanly (a resource modified in a way that makes its current state genuinely incompatible with continued management, or drift combined with a provider limitation that prevents importing the change cleanly): destroy the drifted resource and recreate it fresh from the declared configuration. Highest-risk of the three (real downtime/data-loss potential for a stateful resource), reserved for cases the other two approaches cannot cleanly resolve.
Guardrails to prevent accidental manual changes. IAM (identity and access management) policy restricting WHO can make direct changes to managed resources outside the pipeline's own service identity (the strongest structural guardrail, prevention rather than detection); a documented, enforced policy that any necessary emergency change goes through a bounded, audited emergency-change exception with mandatory reconciliation back into Git; and, as a detection-layer backstop for whatever prevention does not catch, the scheduled drift-detection job above, since prevention alone is never perfectly complete in practice.
Trade-offs and pitfalls
- Common mistake: treating "reapply" as the default remediation for every drift, without first checking whether the LIVE state might actually be the one that should be kept. A drift caused by a legitimate, already-deployed emergency fix should be IMPORTED (formalized into the declaration), not silently reverted by a reflexive reapply; choosing the wrong direction for a specific drift event can undo a real fix.
- Destroy-and-recreate is the highest-risk remediation and should never be the DEFAULT choice for ordinary drift, it is appropriate only when the other two genuinely do not apply; a scheduled drift-remediation process that defaults to destroy/recreate for anything it cannot cleanly reapply risks real, avoidable disruption for drift that a careful import would have resolved safely.
- Scheduled drift detection at real scale needs its OWN rate-limiting and credential-handling discipline, running
planagainst every environment on a fixed schedule without staggering or backoff can itself trigger cloud-provider API throttling, ironically causing the detection job's OWN failures to look like (or mask) real drift if not handled distinctly. - IAM-based prevention is the stronger guardrail but is never complete on its own, break-glass access, third-party integrations with their own write permissions, and provider-side automatic changes (certificate rotation, for instance) all sit outside what IAM restriction alone can prevent; detection remains necessary even with strong prevention in place, not a redundant afterthought.
An operator reports the cluster drifted because someone updated a Deployment directly on the cluster. Using Argo CD, explain how you'd detect this drift, alert the team, and define a policy for auto-sync vs manual reconciliation. Mention concrete Argo CD configuration knobs (e.g., app settings, autoPrune, project restrictions) you'd use.
Sample Answer
Direct answer
Argo CD detects this drift automatically: its application-controller continuously compares the live cluster state against the Git-sourced desired state and marks the Application OutOfSync the moment they diverge, no separate detection mechanism needed, drift detection is the reconciliation loop's core function, not an add-on. What the operator needs to DECIDE is the response policy: whether that drift should be automatically corrected (syncPolicy.automated with selfHeal: true), left for a human to review and manually sync, or actively PREVENTED at the source via Project-level restrictions and RBAC that stop the direct edit from being possible in the first place.
Structured elaboration
Detecting the drift. No extra configuration is needed for detection itself: Argo CD's reconciliation loop diffs live vs. desired state on every poll/watch cycle (typically every few minutes, plus event-driven watches for faster detection on supported resource types) and surfaces the result as the Application's sync status (Synced / OutOfSync) directly in the UI and via the API/CLI, with a resource-level diff showing exactly which fields changed.
Alerting the team. Configure argocd-notifications (or the Notifications controller) to fire on the on-sync-status-unknown / on-app-out-of-sync triggers, routed to Slack/PagerDuty/email, so the team learns about drift proactively rather than discovering it next time someone happens to open the Argo CD UI. Alerting on drift specifically (not just on sync failures) is what catches exactly this "someone edited the cluster directly" scenario, since a manual edit does not fail anything, it just diverges silently until observed.
Auto-sync vs. manual reconciliation policy. The core knob is syncPolicy.automated.selfHeal: true means Argo CD will AUTOMATICALLY revert any detected drift back to the Git-declared state on its next reconciliation pass (the direct edit gets overwritten, enforcing Git as the actual source of truth in practice, not just in principle); false (or automated omitted entirely, requiring manual sync) means drift is detected and surfaced but NOT auto-corrected, leaving a human to decide whether to sync back to Git or, if the manual change was actually a legitimate emergency fix, capture that fix in Git properly and let reconciliation then match it. automated.prune: true additionally ensures resources REMOVED from Git also get removed from the cluster, not just resources CHANGED.
Concrete Argo CD knobs.
| Knob | Effect |
|---|---|
syncPolicy.automated.selfHeal | Auto-revert live drift back to Git state on next reconcile |
syncPolicy.automated.prune | Auto-delete cluster resources no longer present in Git |
syncPolicy.automated (unset) | Manual-sync-only; drift detected and surfaced but not auto-corrected |
project.destinations / clusterResourceWhitelist | Restrict WHAT and WHERE a project's applications can even touch, narrowing where drift can occur |
spec.syncWindows | Restrict WHEN automated sync may fire (e.g. block auto-sync during a change freeze, still allowing manual/emergency sync) |
| RBAC on the target cluster (outside Argo CD itself) | The actual technical control preventing the direct kubectl edit in the first place; Argo CD's own policy cannot stop someone with independent cluster access |
Trade-offs and pitfalls
- Common mistake: treating
selfHeal: trueas strictly "safer" than manual reconciliation for every application. Auto-reverting drift is exactly right for steady-state config, but if the direct edit was a legitimate emergency mitigation (someone scaled up replicas by hand during an incident because the Git-based promotion pipeline was too slow), an aggressive self-heal will silently UNDO that mitigation on the next reconcile, which can make an active incident worse; high-blast-radius or incident-prone applications sometimes deliberately run with manual sync so a human is in the loop before any revert happens. - Detecting drift is not the same as PREVENTING it, and a mature answer addresses both. Alerting-and-reverting is a reactive control; the stronger, complementary control is removing direct cluster-edit capability from anyone who isn't supposed to have it in the first place (RBAC scoped so that the ONLY path to change cluster state is through Git and the GitOps controller's own service account), which is a Kubernetes RBAC concern outside Argo CD's own configuration surface entirely.
- Common mistake: assuming faster polling intervals meaningfully "fix" drift-related risk. Detection latency matters less than the RESPONSE policy; an application drift-detected in 10 seconds but left unaddressed for a day because nobody reviews the alert has the same practical risk exposure as one detected an hour later and immediately reverted.
selfHealreverting a change does not, by itself, explain WHY someone made the direct edit; a mature incident-response process pairs auto-revert with a required postmortem or at least a recorded reason whenever selfHeal fires against a change that wasn't accidental, so the underlying reason for the manual edit (a broken pipeline, a missing self-service path) actually gets fixed rather than just repeatedly reverted.
Explain the key differences between application code and infrastructure-as-code with respect to side effects, idempotency, testing strategies, stateful behavior, and deployment workflows. Why do these differences change how you design Git workflows and code reviews for IaC?
Sample Answer
Direct answer
Application code and infrastructure-as-code (IaC) differ along four axes that all trace back to one root cause: application code typically runs against a FRESH, disposable process each time, while IaC runs against a persistent, STATEFUL external system it must reconcile with, not simply execute from scratch. That single difference is why IaC's side effects are inherently real-world and often hard to undo, why idempotency is a REQUIREMENT rather than a nice-to-have, why testing needs a genuinely different strategy, and why Git workflows and code review for IaC carry more weight per line changed than the equivalent application-code change typically does.
Structured elaboration
Side effects. Application code's side effects (writing to a database, calling an API) are usually scoped to WITHIN a request or process lifecycle and are, in aggregate, reversible by design (a failed deploy just doesn't serve the new code; the old process keeps running). IaC's side effects ARE the actual state of real infrastructure: a resource created, modified, or destroyed persists independent of any process, and some effects (data loss on a destroyed database, an IP address released and reassigned elsewhere) are not reversible by simply "running the old version again."
Idempotency. Well-written application code handles a request; running it twice generally means "handled two requests." IaC tools are explicitly designed to be idempotent by CONTRACT, running apply against an already-matching state should do nothing, this is a foundational property Terraform and similar tools are built around because IaC is normally run repeatedly against the SAME target (every CI run, every scheduled reconciliation), and non-idempotent behavior there would mean re-running a pipeline creates duplicate resources or repeatedly performs an action that should only happen once.
Testing strategies. Application code is tested primarily against IN-MEMORY or locally-mocked dependencies, fast, cheap, run thousands of times per day trivially. IaC testing (unit-level linting/validation, integration tests like terratest that actually provision real or near-real infrastructure) is inherently slower and often costs real money per test run, since meaningfully testing "does this correctly create a VPC" often requires actually creating one, at least in an ephemeral test account.
Stateful behavior. Application code is typically STATELESS between invocations (or explicitly manages its own state via a database, a clearly-owned concern). IaC tools maintain an external STATE FILE representing what they believe is currently deployed, a persistent, shared, lockable artifact with its own consistency and concurrency concerns that has no real analog in typical application-code deployment.
Deployment workflows. Deploying application code usually means: build an artifact, run it, and if something is wrong, roll back by deploying the PREVIOUS artifact, a symmetric, cheap operation. Deploying IaC changes means: compute a PLAN of real-world actions against a stateful system, and "rolling back" is not automatically symmetric, reverting the CONFIGURATION and reapplying can trigger an entirely different, sometimes equally disruptive, set of real actions, not simply "redeploy the old version."
Why these differences change Git workflows and code review design. Because IaC changes have real, sometimes-irreversible side effects on shared, persistent infrastructure, review needs to weigh the PLANNED EFFECT, not just the code diff, and branch protection and approval requirements typically need to be STRICTER for infrastructure changes than for a typical application-code PR of similar size, and the CI validation gate needs to include a real plan/dry-run step application-code CI generally does not have an equivalent of.
Trade-offs and pitfalls
- Common mistake: reviewing an infrastructure PR with the SAME mental model used for application code, reading the diff, checking style and logic, and approving, without separately reading the PLAN OUTPUT that shows the actual real-world effect; this is the single biggest practical consequence of these differences, and "review the plan, not just the diff" is the discipline that closes the gap.
- Idempotency is easy to accidentally break with a poorly-designed custom provisioner or a script-based resource (a
local-execprovisioner running an imperative script) that itself is NOT idempotent, even inside an otherwise well-designed Terraform configuration; the tool's OWN idempotency guarantee does not automatically extend to arbitrary code a configuration chooses to shell out to. - Testing costs real money for IaC in a way application-code testing generally does not, a testing strategy that ignores this (running full integration tests against real cloud resources on every single commit, for every PR, with no cost-aware tiering) is a common, avoidable expense; structuring fast, free checks (lint/validate) for every commit and reserving the expensive, real-infrastructure integration tests for a smaller, gated tier manages this cost directly.
- Treating "rollback" as symmetric for IaC (assume reverting the config is automatically as safe as the original apply was) is a recurring, costly mistake: a revert can trigger the SAME class of disruptive action (a forced destroy-and-recreate) in the opposite direction, not a clean undo.
Create a compliance plan that ensures every infrastructure change is auditable. Include signed commits or tags, branch protection policies, enforced code reviews, immutable release artifacts, retention of CI logs, and centralized change records. How would you demonstrate compliance during an external audit using Git history and CI artifacts?
Sample Answer
Direct answer
Auditable infrastructure change rests on five mechanisms working together, not any single one: signed commits or tags (proving WHO authored a change and that history was not altered after the fact), branch protection (guaranteeing every production-bound change actually went through review), enforced code review (the human judgment layer no automated check replaces), immutable release artifacts (guaranteeing what was reviewed is EXACTLY what got deployed), and CI log retention plus centralized change records (the evidence trail an auditor actually reads). During an external audit, the whole story is told by pointing directly at Git history and CI artifacts rather than a separately maintained change log: git log with signed commits and required-approval metadata IS the change record, and the artifact registry IS the proof of what shipped when.
Structured elaboration
Signed commits or tags. Require GPG- or SSH-signed commits on protected branches (enforced as a required status check, unsigned commits rejected at merge time), so git log --show-signature proves both authorship and that the commit content has not been altered since signing, closing the gap a plain author-name field leaves open (anyone can set their local Git username to anything).
Branch protection policies. Protected branches require at minimum: N approving reviews from someone other than the author, passing status checks (including the policy-as-code and signature checks above), and no force-push or history rewriting. This is what makes "every production-bound change went through review" a structurally enforced fact rather than a documented expectation someone could route around.
Enforced code reviews. Beyond the branch-protection MECHANISM (which enforces that SOME review happened), the POLICY needs to specify who counts as a qualified reviewer for a given path (CODEOWNERS scoping production-infrastructure paths to a smaller, accountable group) and what a reviewer is actually expected to check (a documented review checklist), since an unscoped "any teammate can approve" rule satisfies the branch-protection mechanism without satisfying most compliance frameworks' actual segregation-of-duties intent.
Immutable release artifacts. The artifact that gets deployed (a container image referenced by digest, a Terraform plan file) must be built ONCE, from the reviewed commit, and referenced by an immutable identifier from that point forward; if the artifact could be rebuilt or modified after review, the reviewed diff and the deployed bytes are no longer provably the same thing, which breaks the entire audit chain at its weakest link even if every other control here is correctly implemented.
Retention of CI logs. CI run logs (which checks ran, their results, who triggered the run, exact timestamps) need a retention policy that matches the audit window the compliance framework requires (often one to seven years depending on the regulation), stored somewhere the CI system's own default log rotation will not silently delete before that window closes.
Centralized change records. For most infrastructure-audit purposes, the merged PR itself (title, description, diff, approvals, linked ticket, CI results) IS the centralized change record; a SEPARATE change-management system is only needed if the compliance framework requires change records to exist independently of the engineering tooling itself (some regulated environments do), in which case that system should be populated automatically from the PR/CI data, not maintained as a manually duplicated parallel record that can drift out of sync with what Git actually shows.
Worked example
Demonstrating compliance for a specific past change during an external audit, walking the evidence trail an auditor would actually be shown:
- Find the change.
git log --all --grep="<ticket-id>"or the PR search UI locates the specific merged PR by its linked ticket. - Show the review happened. The PR's approval history (who approved, when, against which commit SHA) demonstrates the required review occurred, and the branch-protection RULE configuration (screenshotted or exported from the Git platform's API) demonstrates that review was structurally REQUIRED, not merely present by coincidence on this one PR.
- Show the commit's integrity.
git log --show-signature <commit-sha>shows the signature verifying both authorship and content integrity. - Show what actually deployed matched what was reviewed. The CI run tied to that exact commit SHA produced an artifact with a specific digest; the deployment record (Argo CD's sync history, or the CI deploy job's log) shows that SAME digest was what actually got applied to production, closing the loop from "this diff was reviewed" to "this exact artifact ran."
- Show the CI checks that gated the merge. The CI run's log (retained per the policy above) shows every required check (policy-as-code, security scan, plan validation) passed before merge was even possible.
Trade-offs and pitfalls
- Common mistake: treating signed commits as sufficient proof of review, when they only prove authorship and integrity, not that review happened. Signing and reviewing are two independent guarantees; both need their own enforcement mechanism (commit signing verification, and branch-protection-required-approvals), and conflating them leaves a real gap an auditor will find.
- A maintained-in-parallel change-management system is a common, avoidable compliance liability. If it is populated by hand rather than automatically from PR/CI events, it WILL eventually drift from what Git actually shows, and an auditor comparing the two systems and finding a discrepancy is a worse outcome than having only the Git-native record in the first place.
- Immutable artifacts are the load-bearing link auditors most often find missing. Even with perfect commit signing and review enforcement, if the deployed artifact could theoretically have been rebuilt from a slightly different commit after review (a mutable tag, a non-reproducible build), the entire chain of evidence has a gap at exactly the step that matters most, "is what I reviewed what actually ran."
- CI log retention needs an explicit owner and a periodic verification that it is actually working, a retention policy that exists only in a document, with nobody having confirmed logs from six months ago are still retrievable, is a compliance gap waiting to be discovered mid-audit rather than beforehand.
Unlock Full Question Bank
Get access to all Infrastructure as Code and GitOps interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.