Interview questions › Infrastructure as Code (Terraform, Ansible)
Infrastructure as Code (Terraform, Ansible) interview questions & answers
100 Infrastructure as Code (Terraform, Ansible) interview questions, from basic to advanced. Each links to a full answer page with a concise spoken answer, a technical explanation, and a hands-on example.
Tip: paste the job description + your resume into our free resume checker to see which of these skills the role actually requires.
Basic questions
- What is Infrastructure as Code, and what problems does it solve over click-ops?Infrastructure as Code is the practice of defining infrastructure in version-controlled files instead of creating it manually through consoles.
- What is the difference between declarative and imperative IaC, and where do Terraform and Ansible fall?Declarative IaC describes the desired end state and lets the tool calculate the changes.
- What is the difference between configuration management and provisioning?Provisioning creates infrastructure such as networks, compute, databases, IAM, and load balancers.
- What is Terraform, and what is the core plan/apply workflow?Terraform is a declarative IaC tool that compares configuration, state, and real infrastructure to produce a plan, then applies that plan to create, update, or delete…
- What does terraform init do?terraform init prepares a working directory.
- What is the Terraform state file, and why is it critical?The Terraform state file is Terraform's source of truth for mapping resource addresses in code to real provider object IDs.
- Why should state be stored remotely, and what backend would you use on AWS?State should be remote so teams share one authoritative state, get locking, enable recovery, and avoid state sitting on a laptop.
- What is state locking, and why does it matter for teams?State locking prevents two Terraform runs from writing the same state at the same time.
- How does Terraform use DynamoDB for state locking with an S3 backend?Historically, Terraform's S3 backend used a DynamoDB table with a LockID partition key to acquire a lock before modifying state and release it afterward.
- What is a Terraform provider, and how is it versioned?A Terraform provider is a plugin that knows how to talk to an API such as AWS, Azure, Kubernetes, GitHub, or Datadog.
- Why pin provider and Terraform versions, and how do you do it?Version pinning makes Terraform runs deterministic.
- What is a Terraform module, and why use modules?A Terraform module is a directory of Terraform configuration that exposes inputs and outputs.
- What is the difference between a root module and a child module?The root module is the Terraform directory where you run terraform plan and apply.
- What are input variables, outputs, and locals?Input variables are parameters passed into a module.
- What is the difference between count and for_each, and when do you use each?count creates N instances addressed by numeric index; for_each creates instances keyed by map or set keys.
- What problem does for_each solve that count creates when removing items?for_each solves the index-shift problem caused by count.
- What is a dynamic block, and when would you use it?A dynamic block generates repeatable nested blocks inside a resource.
- What is the difference between a data source and a resource?A resource tells Terraform to create and manage an object.
- What is terraform import, and when do you need it?terraform import brings an existing real-world object under Terraform state management.
- What is configuration drift, and how does Terraform detect it?Configuration drift is when real infrastructure no longer matches Terraform code or state, usually because of manual changes, external automation, or provider-side…
- How do you handle resources changed manually outside Terraform?For manual changes outside Terraform, I first run plan to understand the drift.
- What are Terraform workspaces, and what are their limitations for environments?Terraform workspaces let the same configuration directory maintain multiple state instances, selected with terraform workspace select.
- What is the difference between using workspaces and separate state files per environment?Workspaces multiplex state within one configuration, while separate state files or directories make environment boundaries explicit.
- How do you structure Terraform code for multiple environments (dev/staging/prod)?I structure multi-environment Terraform with reusable modules plus thin environment root modules.
- What is the purpose of terraform plan -out and applying a saved plan?terraform plan -out writes an exact saved execution plan.
- What does terraform refresh do, and how has its behaviour changed?terraform refresh used to update state to match remote objects, but the standalone command is deprecated.
- What are provisioners, and why are they considered a last resort?Provisioners run scripts or commands during resource creation or destruction.
- What is the difference between local-exec and remote-exec provisioners?local-exec runs a command on the machine executing Terraform.
- What is the lifecycle block (create_before_destroy, prevent_destroy, ignore_changes)?The lifecycle block customizes resource behavior.
- When would you use ignore_changes, and what is the risk?ignore_changes is useful when an external controller manages an attribute, such as an autoscaler changing desired capacity or Kubernetes adding annotations.
- What is a tainted resource, and what replaced the taint command?A tainted resource is a resource marked for replacement on the next plan.
- How do you target a specific resource with terraform apply, and why is it discouraged?You can target a resource using terraform plan or apply -target=resource.address.
- What are explicit versus implicit dependencies, and what does depends_on do?Implicit dependencies come from references, such as an instance using a subnet ID.
Intermediate questions
- How does Terraform build its dependency graph?Terraform builds a dependency graph from resource references, provider configuration, module calls, meta-arguments, data sources, and explicit depends_on edges.
- How do you pass outputs from one module to another?Outputs from one module are passed to another by referencing module.<name>.<output>.
- What is a remote state data source, and what is the security concern with it?A remote state data source reads outputs from another Terraform state.
- How do you manage secrets in Terraform without leaking them into state?You cannot completely avoid secret values in Terraform state if Terraform manages a resource attribute that stores the secret.
- Why does the state file potentially contain sensitive values, and how do you protect it?State can contain sensitive values because providers must record enough information to detect drift and update resources.
- What is the sensitive flag on variables and outputs?The sensitive flag prevents values from being displayed in Terraform CLI output and module outputs, which reduces accidental exposure in logs.
- What are Terraform meta-arguments (count, for_each, provider, depends_on, lifecycle)?Terraform meta-arguments are language features that modify how resources or modules behave.
- How do you test Terraform code (validate, fmt, plan, tflint, terratest)?I test Terraform in layers: terraform fmt for style, validate for syntax and provider schema, tflint for static rules, policy tools for guardrails, plan review for…
- How would you integrate Terraform into a CI/CD pipeline safely?A safe Terraform CI/CD pipeline separates plan and apply, uses remote state locking, assumes least-privilege credentials, publishes the saved plan, requires review…
- What is a policy-as-code check for Terraform (OPA, Sentinel, checkov)?Policy-as-code checks evaluate Terraform plans or configuration against organizational rules.
- How do you handle a Terraform apply that fails halfway through?If apply fails halfway, I do not rerun blindly.
- What is the difference between terraform destroy and removing a resource from code?terraform destroy plans deletion for all resources managed by the current state.
- How do you import existing infrastructure into Terraform at scale?At scale, I import existing infrastructure by inventorying resources, grouping them by ownership and risk, generating resource and import blocks, running plans in…
- What is a Terraform registry module, and how do you evaluate one for production use?A Terraform registry module is a published reusable module from the public or private registry.
- How would you write a reusable module for a standard service?For a reusable service module, I define a clean interface, encode secure defaults, expose only necessary knobs, create outputs needed by downstream systems, and add…
- What is the difference between Terraform and CloudFormation, and when choose each?Terraform is multi-cloud and provider-based, with HCL modules and a broad ecosystem.
- What is OpenTofu, and why did it fork from Terraform?OpenTofu is the community-driven open-source fork of Terraform created after HashiCorp changed Terraform's license to BUSL.
- What is Ansible, and how is it agentless?Ansible is an automation and configuration management tool that runs tasks from a control node against managed hosts.
- How does Ansible connect to managed hosts?Ansible connects to managed hosts using connection plugins, most commonly SSH for Linux/Unix and WinRM for Windows.
- What is an Ansible inventory, and what is the difference between static and dynamic inventory?An Ansible inventory lists the hosts and groups Ansible can manage.
- What is a playbook, a play, and a task?A playbook is a YAML file containing one or more plays.
- What is idempotency in Ansible, and why does it matter?Idempotency means running the same automation multiple times should produce the same final state without unnecessary changes.
- Why is a raw shell or command task not idempotent, and how do you make it safe?Raw shell or command tasks are not inherently idempotent because Ansible cannot know whether the command changed anything.
- What is the creates argument on a command task, and how does it add idempotency?creates is an argument for command or shell-style tasks that tells Ansible to skip the command when a specific file already exists.
- What are Ansible modules, and why prefer them over shell commands?Ansible modules are reusable units that implement desired-state logic for a target system.
- What is a handler, and how is it triggered with notify?A handler is a special task that runs only when notified by a changed task.
- Why do handlers run once at the end rather than immediately?Handlers run once at the end of a play by default so multiple changes can trigger one restart instead of several restarts.
- What are Ansible roles, and what is the standard directory structure?Ansible roles package tasks, handlers, templates, files, defaults, variables, and metadata into reusable units.
- What is the order of variable precedence in Ansible at a high level?At a high level, Ansible variable precedence means more specific and later sources override broader defaults.
- What are group_vars and host_vars?group_vars define variables for a group of hosts, while host_vars define variables for a single host.
- What is Ansible Vault, and how do you protect secrets with it?Ansible Vault encrypts sensitive YAML values or files so secrets can be stored with playbooks without being readable in plaintext.
- What is the difference between a variable and a fact?A variable is a value you define or pass into Ansible.
- How does Ansible gather facts, and how do you use them in conditionals?Ansible gathers facts with the setup module at the start of a play when gather_facts is true.
Advanced questions
- What is a register, and how do you use the result of one task in another?register stores the result of a task in a variable.
- What is the when clause, and how do you write conditional tasks?The when clause makes a task conditional.
- What is a loop in Ansible, and how do you iterate over a list?A loop repeats a task for each item in a list or other iterable.
- What is the serial keyword, and how does it enable rolling updates?serial limits how many hosts in a play are processed at one time.
- What is max_fail_percentage, and how does it protect a rollout?max_fail_percentage stops a play when failures exceed an allowed percentage within a batch.
- What is delegate_to, and when would you use it?delegate_to runs a task on a different host than the current inventory host.
- What is the difference between Ansible roles and collections?A role is a reusable automation structure for tasks, handlers, defaults, and templates.
- What is a Jinja2 template, and how is it used in Ansible?A Jinja2 template is a text file with variables, loops, and conditionals that Ansible renders for each host.
- How do you run an Ansible playbook in check (dry-run) mode?Check mode is Ansible's dry-run mode, invoked with --check.
- What is the difference between state: present and state: latest, and the risk of latest?state: present ensures a package or object exists, usually without upgrading if it is already installed.
- How do you handle host-specific differences across a mixed fleet?For a mixed fleet, I separate common logic from host-specific differences using groups, group_vars, host_vars, facts, OS-family conditionals, role defaults, and…
- How would you orchestrate a rolling, health-checked upgrade across servers with Ansible?For a rolling, health-checked upgrade, I use serial to batch hosts, drain each host from traffic, upgrade packages or deploy artifacts, restart services through…
- How do you integrate Ansible into CI/CD and keep playbooks tested?I integrate Ansible into CI/CD by linting YAML and Ansible rules, testing roles with Molecule or ephemeral instances, running check mode where useful, scanning…
- What is ansible-lint, and what does it catch?ansible-lint is a static analysis tool for Ansible content.
- When would you choose Ansible over Terraform and vice versa?I choose Terraform when I need to provision and own infrastructure lifecycle through cloud APIs.
- Can Terraform and Ansible be used together, and how would you combine them?Terraform and Ansible work well together.
- What is Kustomize, and how does it differ from Helm?Kustomize customizes Kubernetes YAML without templates by composing bases and overlays with patches, generators, labels, and name transformations.
- What is a kustomization.yaml, and what does it define?kustomization.yaml is the control file for Kustomize.
- What is the difference between a base and an overlay in Kustomize?A base is a reusable set of Kubernetes manifests.
- How do overlays customise a base without copying it?Overlays customize a base by referencing it and applying patches or transformations rather than copying the YAML.
- What are strategic merge patches versus JSON 6902 patches in Kustomize?Strategic merge patches are Kubernetes-aware YAML patches that merge fields using Kubernetes schema behavior.
- How does Kustomize handle environment-specific configuration?Kustomize handles environment-specific configuration through overlays, patches, name prefixes or suffixes, namespaces, image overrides, common labels, and generators.
- What are name prefixes/suffixes and common labels in Kustomize?Name prefixes and suffixes modify resource names, commonly to avoid collisions between environments or variants.
- What is a configMapGenerator and secretGenerator, and what is the hash suffix for?configMapGenerator and secretGenerator create ConfigMaps and Secrets from literals, files, or env files.
- Why does the config hash suffix help trigger rolling updates?The hash suffix helps trigger rolling updates because a Deployment that references the generated ConfigMap or Secret sees its Pod template reference change when the…
- How is Kustomize integrated natively into kubectl (kubectl apply -k)?Kustomize is integrated into kubectl.
- When would you choose Kustomize over Helm, and can you use them together?I choose Kustomize when I already have Kubernetes YAML and need clean overlays without templating.
- How does ArgoCD work with Kustomize overlays for multiple environments?Argo CD can point an Application at a Git path containing a Kustomize overlay.
- What are the trade-offs of templating (Helm) versus patching (Kustomize)?Helm templating is flexible but can become complex because the final YAML is generated from templates and values.
- How do you keep IaC DRY across many similar microservices?To keep IaC DRY across many microservices, I use reusable Terraform modules, standard service blueprints, shared Kustomize bases, overlays for differences, Ansible…
- How do you review and approve infrastructure changes safely as a team?I review infrastructure changes safely by requiring plans in pull requests, checking policy and security rules, using saved plans for apply, locking state, separating…
- What recent IaC practice or tool have you adopted, and what did it improve?A recent IaC practice I would highlight is moving from ad-hoc imports and manual reviews to reviewable import blocks, drift detection, and policy-as-code in CI.
- How do you detect and remediate IaC drift continuously rather than only at apply time?Continuous drift detection means regularly comparing desired IaC state with live infrastructure outside normal apply windows.
- How would you onboard an existing manually-built environment into IaC with confidence?To onboard a manually built environment, I inventory resources, identify ownership boundaries, create modules or resource blocks, import in small batches, compare…