Infrastructure as Code (Terraform and Ansible) Interview Questions for DevOps
25 Infrastructure as Code (Terraform and Ansible) questions with answers for devops roles — 6 easy, 13 medium, 6 hard.
About Infrastructure as Code (Terraform and Ansible)
Infrastructure as Code replaces console clicks with reviewed, repeatable code. This topic covers the Terraform workflow, state, remote backends and locking, modules, count versus for_each, imports and drift, and Ansible inventories, playbooks, roles, handlers, idempotency and vault for managing secrets.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is Infrastructure as Code and what are its benefits?
Infrastructure as Code means defining servers, networks, databases and other resources in version-controlled files instead of clicking in a console. Benefits are repeatable environments, code review for infrastructure changes, history and rollback through Git, fewer manual mistakes, faster provisioning and easy disaster recovery. Common tools are Terraform and OpenTofu for provisioning and Ansible for configuration management.
terraform init downloads providers and modules and configures the backend. terraform fmt and validate check style and syntax. terraform plan shows what will be created, changed or destroyed without making changes. terraform apply executes the plan after confirmation. terraform destroy removes all managed resources. In CI, save the plan with -out and apply that exact plan after review.
03
Explain Ansible architecture: inventory, modules and playbooks.
Ansible runs from a control node and connects to managed hosts over SSH, or WinRM for Windows, with no agent needed. The inventory lists hosts and groups. Modules are units of work like apt, copy or service. Playbooks are YAML files containing plays that map host groups to ordered tasks. Variables, templates with Jinja2 and roles organise larger automation.
04
How do you define variables and outputs in Terraform?
Declarative tools describe the end state and the tool works out the steps; imperative tools describe the steps. Terraform is declarative, keeps a state file and is best at provisioning cloud resources. Ansible is procedural with mostly idempotent modules, agentless over SSH, and best at configuring servers and deploying software. Many teams use Terraform to create VMs and Ansible to configure them.
08
What is the Terraform state file and why is it important?
terraform.tfstate maps the resources in your code to real resources in the cloud, storing their IDs and attributes. Terraform compares code, state and reality to decide what to create, change or destroy. Without it Terraform would not know what it manages. It may contain secrets in plain text, so store it in a secure remote backend, never in Git.
09
What is remote state and state locking in Terraform?
Remote state stores the state file in a shared backend such as an S3 bucket, Azure Storage or Terraform Cloud, so the whole team and CI use the same state. Locking prevents two runs from changing state at the same time, avoiding corruption; on S3 it uses a lock file or a DynamoDB table. Enable versioning and encryption on the backend for recovery and security.
A module is a reusable folder of Terraform files with input variables and outputs, for example a vpc module or an eks-cluster module. The root module calls child modules with different values for each environment. Modules reduce duplication and enforce standards across teams. They can come from local paths, Git or the Terraform Registry and should be pinned to versions.
11
What is the difference between count and for_each in Terraform?
count creates N copies indexed by number, such as aws_instance.web[0]. Removing an item in the middle shifts indexes and can destroy and recreate resources unexpectedly. for_each iterates over a map or set of strings and keys each instance by name, such as aws_s3_bucket.b["logs"], so adding or removing one item affects only that item. Prefer for_each for named collections.
Idempotency means running the same playbook many times gives the same result without unwanted changes. Modules check current state first: the apt module installs a package only if missing and reports ok instead of changed. The shell and command modules are not idempotent by default, so use creates, removes or changed_when conditions, or prefer a dedicated module.
A role is a standard folder structure that packages tasks, handlers, templates, files, variables and defaults for one purpose, for example a nginx or postgres role. Playbooks then just list roles for host groups, keeping them short and reusable across projects. Roles can be shared through Ansible Galaxy or collections, and tested with Molecule.
14
You need to bring existing manually created cloud resources under Terraform. How?
Write the resource blocks in code, then import the real resources into state. Since Terraform 1.5 you can declare import blocks with the resource ID and run plan; terraform plan -generate-config-out can even draft the configuration. Older versions use the terraform import CLI command. Run plan until it shows no changes, which proves code matches reality.
15
An Ansible playbook run against 100 servers failed on 7 of them. What do you do?
Check the output and the retry file or failed host list to see the error on those hosts, for example unreachable SSH, a missing package repo or full disk. Fix the cause, then rerun only those hosts with --limit. Because tasks are idempotent, rerunning on successful hosts is also safe. For rolling changes, use serial and max_fail_percentage to stop early on failures.
16
Write Terraform code to create an AWS EC2 instance.
terraform {
backend "s3" {
bucket = "acme-terraform-state"
key = "prod/network/terraform.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true
}
}
Then run terraform init (add -migrate-state if moving local state). Enable versioning on the bucket. Older setups use dynamodb_table = "tf-locks" instead of use_lockfile for locking.
18
What are Ansible handlers and how do you use them?
Handlers are tasks that run only when notified by another task that reported a change, and they run once at the end of the play even if notified many times.
tasks:
- name: Update app config
ansible.builtin.copy:
src: app.conf
dest: /etc/app/app.conf
notify: Restart app
handlers:
- name: Restart app
ansible.builtin.service:
name: app
state: restarted
This avoids restarting services when nothing changed.
19
Tell me about a mistake you made in infrastructure work and what you learned.
Situation: I applied a Terraform change that renamed a security group, which forced replacement and briefly cut access to a staging database. Task: fix it and prevent repeats. Action: I restored access quickly, explained it openly to my lead, and then added plan review in pull requests plus lifecycle create_before_destroy rules. Result: no similar outage since, and I now read every destroy line in a plan.
20
What is configuration drift and how do you detect it with Terraform?
Drift is when real infrastructure differs from code, usually because someone changed it manually in the console. terraform plan, or plan -refresh-only, shows differences between state and reality. Teams run scheduled plans in CI and alert on any diff. Prevent drift by restricting console write access, applying only through pipelines, and either reverting manual changes or codifying them.
21
Two engineers ran terraform apply at the same time. What could go wrong and how do you prevent it?
Without locking, both runs read the same state and write conflicting updates, which can corrupt state or create duplicate resources. Use a remote backend with state locking so the second run waits or fails. Better still, run apply only from a CI pipeline on merge to main, so changes are serialised and reviewed. If a lock is stuck after a crash, use terraform force-unlock carefully.
22
Someone deleted a resource manually that Terraform manages, and the state is now out of sync. What do you do?
Run terraform plan; Terraform refreshes and sees the resource is missing, so it plans to recreate it, which is often right. If the resource should no longer exist, remove it from code, or use terraform state rm. If state itself is corrupted, restore a previous version from the versioned S3 bucket. Then find out why manual changes happened and tighten access.
23
How do you manage dev, staging and production environments with Terraform?
Keep shared logic in versioned modules and create a separate root configuration per environment, each with its own backend state and tfvars, for example envs/dev and envs/prod. This isolates state so a mistake in dev cannot touch prod. Workspaces are an option for near-identical environments but share backend config. Promote module versions from dev to prod through pull requests.
24
How do you handle secrets in Terraform and Ansible?
Do not hard-code secrets in .tf files or playbooks. In Terraform, read them from AWS Secrets Manager or Vault data sources, mark variables sensitive, and protect state because it may still hold values. In Ansible, encrypt secret variable files with ansible-vault and supply the vault password from CI secrets, or look up values from Vault at runtime. Rotate anything exposed in Git.
25
How would you convince a team that manages servers by hand to adopt Infrastructure as Code?
I would start with their pain, such as slow environment setup or outages from manual changes, rather than the tool. Then I would codify one small, visible piece, for example a new staging environment, and show it rebuilt in minutes with a reviewed pull request. I would pair with team members, write simple docs and expand gradually, measuring time saved and incidents avoided.
Frequently asked questions
How important is Infrastructure as Code (Terraform and Ansible) in DevOps interviews?
Infrastructure as Code replaces console clicks with reviewed, repeatable code. This topic covers the Terraform workflow, state, remote backends and locking, modules, count versus for_each, imports and drift, and Ansible inventories, playbooks, roles, handlers, idempotency and vault for managing secrets.
How should I use the Infrastructure as Code (Terraform and Ansible) sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.