DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

Terraform · interview practice

Terraform interview questions

Answer each one out loud first, then tap it to check yourself against a model answer and the lesson behind it.

Introduction 2HCL 2Providers 2Project initialization 3Resources 3Variables & outputs 2Format & validate 1State 4Plan, apply, destroy 3Modules 2Data sources & templates 2Environments 1CI/CD integration 2Testing 2Scaling Terraform 1Security 2Capstone project 2

Introduction

Q1What does infrastructure as code give a team that building resources in the console does not?junior

The environment becomes repeatable, every change goes through a pull request, Git history shows who changed what, and the code describes what exists. It only holds while people stop making changes in the console, because every manual change becomes drift the next plan will try to undo.

Read the lesson: Infrastructure as code, and where Terraform fits →
Q2A team asks whether to use Terraform or Ansible. How do you split the work?junior

Terraform provisions infrastructure through cloud APIs with a state file: VMs, networks, load balancers. Ansible configures what runs inside existing servers over SSH. A common split is Terraform creating the servers and Ansible, cloud-init or a pre-built image setting them up.

Read the lesson: Infrastructure as code, and where Terraform fits →

HCL

Q3How does Terraform decide which resource to create first?junior

It builds a dependency graph from references: if a file's content uses random_pet.server.id, the pet is created first. The order of blocks and files doesn't matter. depends_on is only needed for a dependency no argument refers to.

Read the lesson: HCL: the Terraform language →
Q4What does cidrsubnet("10.0.0.0/16", 8, 2) return, and why do VPC modules use it?mid

It returns "10.0.2.0/24": add 8 bits to the /16 prefix and take subnet number 2, counting from 0. Subnets carved this way follow the VPC range, so changing one CIDR variable moves every subnet instead of editing hand-typed ranges.

Read the lesson: HCL: the Terraform language →

Providers

Q5What does version = "~> 2.9" allow for a provider, and why is it the usual choice?junior

It allows 2.9 and later 2.x releases but not 3.0, because only the rightmost number written may grow. You get fixes and new features without a major release that can rename arguments, and the lock file then pins the exact build actually used.

Read the lesson: Providers and version pinning →
Q6Most of your stack is in ap-south-1, but a CloudFront certificate must live in us-east-1. How do you do that in one configuration?mid

Add a second provider "aws" block with alias = "us_east_1" and that region, and set provider = aws.us_east_1 on the certificate resource. Resources without a provider argument keep using the default, un-aliased configuration.

Read the lesson: Providers and version pinning →

Project initialization

Q7Which files in a Terraform project belong in Git, and which do not?junior

Commit the .tf files and .terraform.lock.hcl. Ignore .terraform/, which is a provider and module cache anyone can rebuild with init, state files, which can hold secrets, and saved plan files, which contain every value in the plan.

Read the lesson: terraform init and the lock file →
Q8What is the difference between a version constraint and the lock file?mid

The constraint in required_providers says which versions are allowed; the lock file records the exact version chosen and its hashes, so every machine installs the same build. Versions only move when someone runs terraform init -upgrade and commits the new lock file.

Read the lesson: terraform init and the lock file →
Q9You changed the backend block and init asks for -reconfigure or -migrate-state. How do you choose?senior

-migrate-state copies the existing state to the new backend, which is what you want when moving from local to S3. -reconfigure ignores the old backend, which is right only when the new one already holds the correct state. Choosing wrong can leave an empty state, so back up the old one first.

Read the lesson: terraform init and the lock file →

Resources

Q10Why is for_each usually safer than count for a list of named servers?mid

count addresses resources by position, so removing the first item shifts every later item to a new index and they get replaced. for_each addresses by key, so only the removed key is destroyed. Keep count for N identical copies or a 0/1 switch.

Read the lesson: Resources: count, for_each and lifecycle →
Q11A plan shows -/+ on a resource you only meant to tweak. What do you do before approving?mid

Find the argument marked # forces replacement: the provider can't change it in place, so the old object goes away, maybe with its data. Then decide: accept it with create_before_destroy to avoid downtime, revert the change, or use a moved block if only the address changed.

Read the lesson: Resources: count, for_each and lifecycle →
Q12What does prevent_destroy protect against, and what does it not?senior

Any plan that would destroy the resource fails, and the whole run stops, which forces a reviewed code change. It only guards against Terraform and against accidents: someone can delete the line, so stateful resources also need the cloud's own protection, such as deletion_protection on RDS.

Read the lesson: Resources: count, for_each and lifecycle →

Variables & outputs

Q13A variable is set by TF_VAR_, terraform.tfvars and -var at the same time. Which value wins?junior

The command line wins: -var and -var-file, in the order written, beat *.auto.tfvars, which beat terraform.tfvars, which beats TF_VAR_ environment variables and then the default. Teams usually keep one tfvars file per environment and pass it with -var-file in CI.

Read the lesson: Variables, locals and outputs →
Q14When do you use variable validation, a precondition, a postcondition or a check block?senior

Validation checks one input before planning and blocks the run. A precondition checks any assumption, such as a relation between variables, before that resource is planned; a postcondition checks the resource's own result with self. A check block only warns, so it is monitoring, never a safety gate.

Read the lesson: Variables, locals and outputs →

Format & validate

Q15terraform validate passes but instance_type = "t3.mirco" is a typo. Why, and what catches it?junior

validate only checks structure against the provider schema: the argument name is right and the value is a string. TFLint with the AWS ruleset knows the real instance types and reports it as an error. Without it you find out at apply time, halfway through creating other resources.

Read the lesson: fmt, validate and TFLint →

State

Q16Why can Terraform not work without a state file?junior

State maps each address in the code, like aws_instance.web, to the real object ID it created, and caches its attributes and dependencies. Without it Terraform can't tell its server from everyone else's, so it couldn't update or delete safely. It can hold secrets, so it never goes in Git.

Read the lesson: State: Terraform's memory →
Q17How do you set up shared state for a team on AWS?mid

An S3 backend with a key per environment, encrypt = true and use_lockfile = true for native locking, which replaced the now-deprecated DynamoDB table in Terraform 1.10. Create the bucket once, outside the configuration, with versioning on and public access blocked, and restrict who can read it.

Read the lesson: State: Terraform's memory →
Q18You renamed local_file.web to local_file.frontend. How do you avoid a destroy and create?mid

Add a moved block from the old address to the new one; the plan says "has moved" and changes nothing real. terraform state mv does the same directly on state, but the moved block is reviewed in a pull request and works for every environment that runs the code.

Read the lesson: State: Terraform's memory →
Q19Someone built a resource by hand and you need Terraform to manage it. Walk through it.senior

Write the resource and an import block with its real ID, in the format the provider docs give, and plan -generate-config-out can draft the code. After applying the import, the next plan must say No changes; if it wants changes, the code doesn't match reality yet. Some resources don't support import at all.

Read the lesson: State: Terraform's memory →

Plan, apply, destroy

Q20Why apply a saved plan file instead of running terraform apply on its own?mid

terraform apply tfplan does exactly what was reviewed, and refuses with "Saved plan is stale" if the state changed since. A plain apply makes a fresh plan, which may differ from what you read. The plan file holds every value, secrets included, so it must be kept private and short-lived.

Read the lesson: Plan, apply and destroy →
Q21The plan shows drift from a manual change. How do you decide what to do?mid

If the manual change was a mistake, apply and Terraform puts the code's version back. If it was right, put it in the code so the plan shows no changes. plan -refresh-only shows only the drift, and apply -refresh-only accepts it into state without touching real resources.

Read the lesson: Plan, apply and destroy →
Q22When is -target acceptable?senior

Only to recover from a broken state or for an urgent fix. It applies a partial plan, so the rest of the configuration and its state drift apart. Run a full plan straight after, and on production get a second person to agree before using it.

Read the lesson: Plan, apply and destroy →

Modules

Q23Why does a child module declare required_providers but have no provider block?mid

Configuring providers is the root module's job, and child modules inherit them. That keeps the module reusable across regions and accounts. The module exposes only its outputs, read as module.<name>.<output>, so callers never reach into its resources.

Read the lesson: Modules: reusable infrastructure →
Q24How do you release a change to a shared module without hitting production first?senior

Release it with a semantic version tag and have every caller pin a version: version for registry sources, ?ref= a tag for Git sources. Upgrade dev, then staging, then prod in separate pull requests, running terraform init -upgrade and reading each plan. A breaking input change is a major bump.

Read the lesson: Modules: reusable infrastructure →

Data sources & templates

Q25What is the difference between a resource and a data source?junior

A resource is created, changed and destroyed by Terraform. A data source only reads something that already exists, such as the latest Ubuntu AMI or another team's VPC, during plan. If what it looks for doesn't exist, the plan fails, which is a useful early check.

Read the lesson: Data sources, templates and provisioners →
Q26Why are provisioners a last resort, and what do you use instead?mid

The plan can't show what a script will do, they run on create only so they aren't idempotent, and a failure taints the resource. Use cloud-init user_data for boot setup, a Packer image, Ansible for ongoing configuration, or a pipeline step after apply for migrations.

Read the lesson: Data sources, templates and provisioners →

Environments

Q27Workspaces or a folder per environment for dev, staging and prod?senior

Folders: each environment has its own backend, can use different credentials or accounts, and its differences are visible in review. Workspaces share one backend and credentials, and it's easy to apply in the wrong one. They suit short-lived copies like a per-PR environment.

Read the lesson: Environments: workspaces or folders →

CI/CD integration

Q28In a pipeline, how do you guarantee that the plan someone approved is what gets applied?senior

Plan on main with -out=tfplan, pass that exact file to the apply job as an artifact from the same run, and run terraform apply tfplan behind a protected environment. Same commit means the same lock file; a stale plan is refused, and concurrency stops two runs against production at once.

Read the lesson: Terraform in CI/CD →
Q29Is the CI plan role really read-only?senior

No. A plan reads every managed resource, but with the S3 backend and use_lockfile it also creates and deletes a .tflock object to hold the lock. It needs read on the state key and write on the lock key, but must not be able to write the state object or change infrastructure.

Read the lesson: Terraform in CI/CD →

Testing

Q30How do you prove with terraform test that a module rejects bad input?mid

Write a run that sets the bad value, say pages = [], and lists var.pages in expect_failures. The run passes only if that validation fails, so deleting the rule later breaks the test. command = plan keeps it fast and free; apply runs create real resources and are destroyed at the end.

Read the lesson: Testing Terraform code →
Q31When is an integration test with Terratest worth the cost?senior

For shared modules many teams depend on, where you need proof the real infrastructure works, such as the load balancer answering on port 80. They apply real resources, take minutes and cost money, so run them on a schedule or before a release, in a separate test account with a budget alarm.

Read the lesson: Testing Terraform code →

Scaling Terraform

Q32After splitting state, why not read the network outputs with terraform_remote_state everywhere?senior

It shows only outputs, but downloads the whole state snapshot, so the reader needs access to every secret in it and is coupled to that backend. Publishing values to SSM parameters or looking resources up by tag gives a narrower contract; remote state fits inside one team.

Read the lesson: Scaling Terraform: split state, Terragrunt, Infracost →

Security

Q33A variable is marked sensitive = true. Is the secret safe?mid

It is only redacted from plan output and CI logs. terraform output -raw prints it in clear, and the state and any saved plan hold it in plain text. Those files need the same protection as the secret: an encrypted remote backend and tight access.

Read the lesson: Terraform security: secrets, scanning and policy →
Q34How do you get a database password to AWS without it ever landing in Terraform state?senior

Read it with an ephemeral resource, such as ephemeral "aws_secretsmanager_secret_version", and pass it through a write-only argument like password_wo, bumping password_wo_version to rotate. That needs Terraform 1.11 and a provider that supports it; letting RDS manage the password is also an option.

Read the lesson: Terraform security: secrets, scanning and policy →

Capstone project

Q35How would you plan an AWS configuration in CI without any AWS credentials?senior

A git-ignored file ending in _override.tf merges fake credentials and skip flags into the provider and swaps the backend to local, and the AMI is passed as a variable so no data source calls AWS. It proves the code is complete and consistent, but not that AWS will accept it.

Read the lesson: Capstone: AWS infrastructure with Terraform →
Q36When is it acceptable to suppress a security scanner finding?mid

When the choice is deliberate, such as a public load balancer, and the suppression names the finding ID with a written reason that gets reviewed like code. An ignore with no finding behind it should be removed, because it only hides future mistakes.

Read the lesson: Capstone: AWS infrastructure with Terraform →
← Back to the Terraform course