MyInternships.in
40 QUESTIONS · JUNIOR TO SENIOR · WITH ANSWERS

Terraform & Infrastructure as Code on GCP Interview Questions and Answers

Terraform is the assumed default for provisioning GCP, so these questions come up in every cloud engineer and DevOps interview: state, modules, workspaces, drift, imports, and the failure modes that only appear on a real team.

1 junior7 mid-level32 senior

How to use this set

Every question below is written the way an interviewer actually phrases it, followed by a model answer you could say out loud in 30–60 seconds, and — where it helps — the reason the question is asked and the trap most candidates fall into. Questions are tagged Junior, Mid or Senior so you can skip to your level.

This is one of 25 topic sets in the complete GCP interview questions guide. Work through the fundamentals first, then the services your target role actually uses.

1
Junior level

What is Infrastructure as Code and why does it matter?

Answer: Infrastructure as Code means defining infrastructure in version-controlled, declarative files that a tool applies, rather than clicking in a console. It matters because it makes environments reproducible, changes reviewable, drift detectable and rollback possible, and it turns infrastructure knowledge from something in people's heads into something in a repository.

Why interviewers ask this: The specific failure it prevents is the unreproducible environment: production configured by hand over three years that nobody can recreate. Naming reviewability — an infrastructure change getting the same scrutiny as a code change — is the point interviewers value most.

2
Mid level

What is Terraform state and why does it exist?

Answer: State is Terraform's record of which real resources correspond to which configuration blocks, along with their last-known attributes. It exists because Terraform must map declarative configuration to actual resource identifiers, detect what changed, and know what to destroy when a block is removed.

Why interviewers ask this: The consequence to name is that state is authoritative and dangerous: losing it means Terraform no longer knows it owns those resources and will try to recreate them. That is why remote state with versioning is not optional on a real project.

3
Mid level

How do you store Terraform state for a team on GCP?

Answer: In a Cloud Storage backend with object versioning enabled, in a dedicated project with restricted IAM. The GCS backend provides state locking natively, so concurrent applies cannot corrupt state, and versioning gives you recovery from an accidental corruption or deletion.

Why interviewers ask this: The three requirements are remote, locked and versioned. Local state on a laptop breaks the moment a second person joins, and unversioned remote state means a bad apply is unrecoverable. Naming all three, rather than just "use a GCS backend", is the complete answer.

HCL
terraform {
  backend "gcs" {
    bucket = "tf-state-prod"
    prefix = "network/prod"
  }
}
4
Senior level

What is state locking and what happens without it?

Answer: Locking prevents two applies from running against the same state simultaneously. Without it, concurrent applies can interleave writes and produce corrupted state where Terraform's record no longer matches reality — leading to duplicated or orphaned resources that must be reconciled by hand.

Why interviewers ask this: The GCS backend implements locking with object preconditions, so it works without a separate lock table. The operational detail worth knowing is force-unlock, for when a process dies mid-apply and leaves a stale lock — and that using it while an apply is genuinely running is how you corrupt state.

5
Mid level

What is the difference between terraform plan and terraform apply?

Answer: Plan computes the difference between configuration, state and reality, and shows what would change without changing anything. Apply executes those changes. In a pipeline, plan runs on every pull request for review and apply runs after merge and approval, ideally against a saved plan file so the applied change is exactly the reviewed one.

Why interviewers ask this: Applying a saved plan file is the detail that matters for safety: without it, the world can change between plan and apply, so the applied change may differ from the reviewed one. That is a genuine risk in a busy environment.

6
Mid level

What is a Terraform module and how should you structure them?

Answer: A module is a reusable, parameterised group of resources with defined inputs and outputs. Structure them by capability — a network module, a GKE module, a service module — versioned in a registry or a Git repository with tags, and consumed by thin root configurations per environment that supply environment-specific variables.

Why interviewers ask this: The anti-pattern to name is a single monolithic module that takes fifty variables and tries to configure everything, which is harder to reason about than the raw resources. Modules should encapsulate a decision, not merely group resources.

7
Senior level

How do you manage multiple environments in Terraform?

Answer: Separate state per environment — separate backend prefixes or separate buckets — with a root configuration per environment that instantiates shared modules with different variable values. Terraform workspaces are an alternative but keep all environments in one state file lineage, which is generally worse for isolation and blast radius.

Why interviewers ask this: The argument against workspaces for environments is blast radius and access control: with separate state and separate service accounts, a production apply cannot touch development, and permissions can differ. That isolation is the reason most teams end up with directory-per-environment.

8
Senior level

What is drift and how do you detect and handle it?

Answer: Drift is divergence between the state Terraform recorded and the real infrastructure, caused by manual changes or by another system. Detect it by running terraform plan on a schedule and alerting on non-empty plans. Handle it by either reverting the manual change with an apply, or by updating the configuration if the change was intentional.

Why interviewers ask this: The organisational fix is removing standing human write access so drift cannot occur, with a break-glass path that is audited. Detection alone means finding the same class of problem repeatedly; prevention is what actually solves it.

9
Senior level

How do you bring an existing resource under Terraform management?

Answer: Write the configuration to match the resource, then use terraform import — or, in modern Terraform, an import block in configuration so the import is planned and reviewed like any other change. Run plan afterwards and iterate on the configuration until the plan is empty, which proves the configuration matches reality.

Why interviewers ask this: The "iterate until the plan is empty" discipline is the substance: an import that leaves a non-empty plan means your next apply will change the resource, possibly destructively. Import blocks are the improvement to name because they make the operation reviewable rather than a side-effecting CLI command.

HCL
import {
  to = google_storage_bucket.assets
  id = "my-project/assets-bucket"
}
10
Senior level

What is the difference between count and for_each?

Answer: count creates instances indexed by number, so resources are addressed as resource[0], resource[1]. for_each creates instances keyed by a map or set key, addressed as resource["name"]. for_each is almost always better because removing a middle element with count shifts every subsequent index and causes Terraform to destroy and recreate resources unnecessarily.

Why interviewers ask this: That index-shifting destruction is exactly the failure interviewers are testing for — it is a well-known way to accidentally delete production resources. Recommending for_each with a stable key as the default is the correct answer.

11
Mid level

What are Terraform providers and how should you version them?

Answer: A provider is a plugin that implements resource types for a platform — the Google provider, the Google Beta provider, Kubernetes, Helm. Pin provider versions with a required_providers block and a version constraint, and commit the dependency lock file so every run and every engineer uses identical provider versions.

Why interviewers ask this: The lock file is the part frequently missed: without it, a provider upgrade can change generated plans unexpectedly, and a plan reviewed on one machine may not match the apply on another. Naming the lock file specifically is a good signal.

12
Senior level

What is the Google Beta provider and when do you use it?

Answer: The Google Beta provider exposes resources and fields that are in beta and not yet in the GA provider. You use it when you need a preview feature, declaring it alongside the GA provider and setting provider = google-beta on the specific resources that need it.

Why interviewers ask this: The caution to state is that beta resources can change or be removed, so relying on them in production carries upgrade risk. Using it selectively per resource rather than globally is the practice that limits exposure.

Preparing for a GCP role?

Browse live GCP cloud internships and fresher jobs hiring across India right now.

Cloud Engineer Jobs
13
Senior level

How do you handle secrets in Terraform?

Answer: Do not put them in configuration or variables files. Reference Secret Manager and let the resource read the secret, or have the workload fetch it at runtime so Terraform never touches it. Mark variables sensitive to keep them out of console output, and remember that state contains all attribute values in plaintext, so the state bucket must be treated as a secret store.

Why interviewers ask this: The state-contains-secrets point is the one that catches people: even with sensitive marking, the value is written into state. That is why state buckets need restricted IAM, CMEK and no public access — and why the best answer is to keep secrets out of Terraform entirely.

14
Mid level

What is a data source and how does it differ from a resource?

Answer: A resource is something Terraform creates and manages. A data source reads existing information — an existing project, network, image or secret — without managing it. Data sources are how one configuration references infrastructure owned by another team or another state.

Why interviewers ask this: The alternative for cross-state references is a remote state data source, which reads outputs from another Terraform state. The trade-off to name is coupling: remote state creates a dependency on another team's state file structure, whereas a data source looking up by name is looser.

15
Senior level

How do you structure Terraform for a large organisation?

Answer: Split state by blast radius and change rate — foundation (organisation, folders, IAM), networking, shared platform (clusters, registries), and per-application state — each with its own backend prefix and service account. Share versioned modules from a private registry, use a pipeline for plan and apply with approval on production, and reference across boundaries through data sources or published outputs.

Why interviewers ask this: The blast-radius principle is the answer: a single monolithic state means every change plans against everything, applies are slow, and one mistake can affect the whole estate. Splitting by change rate is the complementary reason — networking changes rarely, applications change daily.

16
Senior level

What happens if terraform apply fails halfway through?

Answer: Terraform records the resources it did create in state, so the state reflects partial progress and a re-run continues from there rather than starting over. If a resource was created but its state write failed, it becomes orphaned and must be imported or manually removed. Resources with failed provisioners are marked tainted.

Why interviewers ask this: The orphaned-resource case is the one worth explaining: the resource exists in the cloud but not in state, so a re-apply tries to create it again and fails on a name conflict. Recognising that symptom and knowing import is the fix is a strong practical signal.

17
Senior level

What is a lifecycle block and what does prevent_destroy do?

Answer: The lifecycle block controls how Terraform handles a resource's lifecycle: create_before_destroy for zero-downtime replacement, prevent_destroy to make Terraform error rather than delete a resource, ignore_changes to tolerate attributes modified outside Terraform, and replace_triggered_by to force replacement when a dependency changes.

Why interviewers ask this: prevent_destroy on production databases and state buckets is a cheap, high-value guardrail. The caveat is that it blocks the whole apply rather than skipping the resource, so it also stops legitimate refactors until you remove it deliberately — which is the point.

18
Senior level

What is ignore_changes and when is it appropriate?

Answer: It tells Terraform not to plan changes for specified attributes, so modifications made outside Terraform are tolerated. It is appropriate where another system legitimately owns an attribute — an autoscaler adjusting node count, a controller adding labels — and inappropriate as a way to hide drift you should have fixed.

Why interviewers ask this: The distinction is intent: ignoring a field genuinely managed elsewhere is correct, while ignoring a field because the plan is inconvenient hides real divergence. Interviewers use this to see whether you reach for it as a tool or as a workaround.

19
Senior level

How do you test Terraform code?

Answer: Static checks first — terraform validate, fmt, and a policy tool such as Sentinel, OPA or Terraform's native test framework. Then plan review in the pull request. Then integration tests with Terratest or terraform test that provision into a sandbox project, assert on the result and destroy. Also scan for security misconfigurations with a tool like tfsec or Checkov.

Why interviewers ask this: The layered approach is the answer, and the honest note is that integration testing infrastructure is slow and expensive, so it is reserved for modules rather than every root configuration. Policy-as-code catching a public bucket at plan time is the highest value per unit effort.

20
Senior level

What is policy as code and how would you apply it to Terraform on GCP?

Answer: Policy as code evaluates the plan against rules before apply — no public buckets, no external IPs, required labels, only approved regions and machine types — failing the pipeline when violated. Tools include OPA/Conftest, Sentinel and Checkov, and on GCP it complements organisation policy constraints.

Why interviewers ask this: The distinction from organisation policy is worth stating: org policy enforces at the API regardless of the tool, while plan-time policy gives fast feedback in the pull request. Both are useful — one prevents, the other teaches — and defence in depth means using both.

21
Senior level

What is the difference between Terraform and Config Connector on GCP?

Answer: Terraform is a general-purpose provisioning tool that runs a plan-and-apply cycle when you invoke it. Config Connector represents GCP resources as Kubernetes custom resources managed by a controller that continuously reconciles them, so drift is corrected automatically without a scheduled run.

Why interviewers ask this: The trade-off is that Config Connector makes a GKE cluster a dependency for provisioning infrastructure, which is a circular dependency if that cluster is itself managed there. Terraform for foundation and Config Connector for application-adjacent resources is a common split.

22
Senior level

What is Infrastructure Manager on GCP?

Answer: Infrastructure Manager is Google's managed Terraform service. It runs terraform plan and apply as a managed operation with state stored and managed by Google, integrated with IAM and Cloud Build, so you do not operate your own state backend or runner.

Why interviewers ask this: It is a reasonable choice for teams that want managed Terraform without adopting a third-party platform. The consideration to name is portability and ecosystem — a self-managed backend with your own pipeline gives more control and works identically across clouds.

23
Senior level

How do you handle a resource that must be replaced but cannot have downtime?

Answer: Use create_before_destroy in a lifecycle block so the replacement is created before the old one is destroyed, which requires that names or other unique attributes do not collide — often solved with a name_prefix or a random suffix. For resources where that is impossible, plan a manual migration with traffic shifting rather than letting Terraform do the swap.

Why interviewers ask this: The name-collision constraint is what makes create_before_destroy fail in practice, and knowing that is what separates people who have used it from people who have read about it. Naming the name_prefix pattern shows you have hit and solved it.

24
Senior level

What are Terraform outputs and how are they used across configurations?

Answer: Outputs expose values from a module or root configuration — a network name, a cluster endpoint, a service account email. Other configurations consume them through a terraform_remote_state data source, or the values are published to a parameter store that consumers read, which decouples them from another team's state file.

Why interviewers ask this: The coupling caution is worth stating: reading another team's remote state means their refactor can break your configuration, and it requires read access to their state, which contains secrets. Publishing to a neutral location is looser and safer.

Preparing for a GCP role?

Browse live GCP cloud internships and fresher jobs hiring across India right now.

Cloud Engineer Jobs
25
Senior level

How do you provision a GKE cluster and its workloads with Terraform?

Answer: Provision the cluster and node pools with the Google provider, then either hand off workload deployment to a GitOps tool such as Config Sync, or use the Kubernetes and Helm providers in a separate configuration and state. Do not put cluster creation and workload deployment in the same state.

Why interviewers ask this: The reason for the split is a genuine chicken-and-egg problem: the Kubernetes provider needs the cluster endpoint and credentials, which do not exist until the cluster is created, and mixing them causes plan failures and destroy ordering problems. This is one of the most commonly hit Terraform pitfalls on GCP.

26
Senior level

What is terraform taint / replace and when do you use it?

Answer: The modern form is terraform apply -replace=ADDRESS, which forces Terraform to destroy and recreate a specific resource on the next apply. It is used when a resource is in a bad state that Terraform cannot detect — a corrupted VM, a failed provisioner — and recreation is the fix.

Why interviewers ask this: The caution is that it is an imperative escape hatch in a declarative tool, so overuse suggests the configuration does not capture the real desired state. Preferring -replace on the command line over the deprecated taint command, and documenting why it was needed, is the disciplined use.

27
Senior level

How do you manage Terraform for hundreds of GCP projects?

Answer: Use a project factory module that creates a project with standard labels, APIs, IAM, budget, log sink and network attachment from a small input set, driven by a data file listing projects. Keep foundation state separate from per-project state, use a pipeline with approval, and generate per-project configurations rather than hand-writing them.

Why interviewers ask this: Naming the Cloud Foundation Toolkit project factory, or the Fabric FAST blueprints, is a strong signal because those are the maintained implementations of exactly this pattern. Hand-writing a configuration per project is what does not scale.

28
Senior level

What are the risks of running terraform apply from a developer laptop?

Answer: Inconsistent provider and Terraform versions producing different plans; personal credentials with more permission than the change needs; no audit trail of who applied what; no review of the plan; and state locking conflicts if several people do it. The fix is applying only from a pipeline with a dedicated service account.

Why interviewers ask this: The audit-trail point matters most in a regulated environment: an apply from a laptop is attributable only through cloud audit logs, with no link to a reviewed change. Removing human apply permission entirely is the strong version of the control.

29
Mid level

What is a dependency in Terraform and how does it decide ordering?

Answer: Terraform builds a dependency graph from implicit references — where one resource's configuration reads another's attribute — and applies resources in that order, parallelising independent ones. depends_on adds an explicit dependency for cases where the relationship is not expressed through an attribute reference.

Why interviewers ask this: The advice is to prefer implicit dependencies through references, because they are self-documenting and correct by construction. Overusing depends_on serialises the graph unnecessarily and often hides a configuration that should have referenced an attribute directly.

30
Senior level

How do you roll back an infrastructure change made with Terraform?

Answer: Revert the commit and apply the previous configuration, which is why version control is the rollback mechanism. That works for most changes, but not for destructive ones — a deleted database is not restored by reverting the code — so destructive changes need prevent_destroy, backups and an approval gate rather than reliance on rollback.

Why interviewers ask this: Being explicit that Terraform rollback is not universal is the mature answer. Interviewers ask this to see whether you understand that "infrastructure as code gives you rollback" is only true for non-destructive changes, which is a meaningful limitation.

31
Senior level

What is the difference between Terraform and Pulumi or CDK-style tools?

Answer: Terraform uses HCL, a purpose-built declarative language, while Pulumi and CDK-style tools let you define infrastructure in a general-purpose programming language. The general-purpose approach gives loops, abstractions and testing in a familiar language; HCL constrains what you can express, which keeps configurations readable and reviewable.

Why interviewers ask this: The trade-off to state honestly is that unlimited expressiveness makes infrastructure code harder to review — a plan is still the source of truth, but you can no longer read the configuration and know what it will do. Team familiarity and review culture usually decide it.

32
Senior level

How do you handle Terraform for resources that GCP creates automatically?

Answer: Either import them so Terraform manages them, exclude them from Terraform's scope entirely and document that they are managed by the platform, or use ignore_changes for attributes the platform mutates. The wrong approach is to let Terraform fight the platform, producing a plan that never converges.

Why interviewers ask this: The never-converging plan is the symptom to recognise: every plan shows the same change because something else reverts it after each apply. Diagnosing that as ownership conflict rather than a Terraform bug is the insight.

33
Senior level

What is a Terraform provisioner and why should you avoid it?

Answer: A provisioner runs a script on or against a resource after creation — remote-exec, local-exec, file. They should be avoided because they are not declarative, do not participate properly in the plan, cannot be re-run idempotently, and leave resources tainted on failure. Use startup scripts, custom images or a configuration management tool instead.

Why interviewers ask this: HashiCorp's own documentation calls them a last resort, and citing that is a strong answer. The GCP-specific alternative is metadata startup scripts or a baked image built with Packer, which is both more reliable and faster to boot.

34
Senior level

How do you keep Terraform modules reusable across teams?

Answer: Version them with Git tags or a private registry and pin versions in consumers; expose a minimal, well-documented variable interface with sensible defaults; avoid embedding environment-specific values; provide outputs consumers actually need; include examples and automated tests; and maintain a changelog with a clear deprecation policy.

Why interviewers ask this: Pinning versions is the operational requirement that makes shared modules safe: without it, a module change breaks every consumer simultaneously. A deprecation policy is what lets you evolve the interface without breaking teams unexpectedly.

35
Senior level

What is a Terraform plan file and why apply from one?

Answer: terraform plan -out=tfplan saves the computed plan to a file, and terraform apply tfplan executes exactly that plan. It guarantees that what was reviewed is what is applied, even if the configuration or the real infrastructure changed in between — the apply fails rather than doing something different.

Why interviewers ask this: This is the control that makes plan review meaningful in a pipeline. Without it, a reviewer approves a plan and the apply recomputes a potentially different one, which quietly undermines the whole review step.

36
Senior level

How would you migrate from click-ops to Terraform on an existing GCP estate?

Answer: Inventory resources with Cloud Asset Inventory; prioritise by risk and change frequency; start with a low-risk domain to build the pattern; generate configurations with terraformer or by hand, import them, and iterate until the plan is empty; then remove human write access to that domain so drift cannot reappear. Repeat domain by domain rather than attempting the whole estate at once.

Why interviewers ask this: The critical step is removing write access after each domain is imported, otherwise manual changes continue and the import work is wasted. Sequencing by domain rather than big-bang is what makes the project finishable.

Preparing for a GCP role?

Browse live GCP cloud internships and fresher jobs hiring across India right now.

Cloud Engineer Jobs
37
Senior level

What is the difference between terraform destroy and removing a resource block?

Answer: terraform destroy removes everything in the state. Removing a resource block from configuration causes the next apply to destroy just that resource. To stop managing a resource without deleting it, use a removed block, or previously terraform state rm, which drops it from state and leaves it in place.

Why interviewers ask this: The removed block is the modern, reviewable equivalent of state rm and is worth naming because it makes the operation part of the plan rather than an out-of-band CLI action. Confusing "remove from state" with "delete the resource" is a genuinely dangerous mistake.

38
Senior level

How do you manage IAM bindings safely in Terraform?

Answer: Prefer google_project_iam_member, which manages a single binding additively, over google_project_iam_policy, which is authoritative and will remove every binding not in your configuration. google_project_iam_binding is authoritative for one role. The authoritative resources can lock you out of your own project if applied carelessly.

Why interviewers ask this: This is a well-known foot-gun and a favourite interview question, because applying an authoritative policy resource without including existing bindings removes everyone's access, including the service account performing the apply. Knowing the three resource types and their scopes is essential.

39
Senior level

What would you include in a pull request template for infrastructure changes?

Answer: The plan output, the reason for the change, blast radius and affected environments, whether any resource is being replaced or destroyed, a rollback plan, and confirmation that policy checks and security scanning passed. Destructive changes should require an explicit acknowledgement.

Why interviewers ask this: Highlighting replacements and destroys specifically is the most valuable element, because a plan is long and the destructive lines are easy to miss. Some teams automate a check that fails the pipeline when a destroy appears without an explicit label, which is the enforced version.

40
Senior level

Design the Terraform setup for a company adopting GCP from scratch.

Answer: A foundation configuration creating the organisation hierarchy, folders, organisation policies, billing export, log sinks and the shared VPC, in its own state with tightly restricted apply access. A project factory module producing standardised projects. Shared versioned modules in a private registry for network, GKE, Cloud SQL and service patterns. Per-application root configurations with state split by environment and blast radius, each with its own least-privilege service account. Pipelines running validate, fmt, security scanning and policy-as-code on every pull request, posting the plan, and applying a saved plan file after merge with approval on production. Remote state in versioned, CMEK-encrypted GCS buckets in a dedicated project, and no human apply access outside break-glass.

Why interviewers ask this: The closing scenario. The senior markers are splitting state by blast radius, per-environment identities, applying from a saved plan file, and removing human apply access — because the most common real-world weakness is a well-structured Terraform repository that anyone can still bypass from a laptop.

Continue your GCP interview prep

See all 25 GCP topics →

Ready to apply for GCP roles?

Cloud internships and fresher jobs across India — filtered to roles that actually name GCP in the requirements.

Cloud Engineer Jobs

Canonical: https://myinternships.in/gcp-interview-questions/terraform-and-iac