Skip to content

Learn. Practice. Feel prepared.

Terraform Interview Questions - Practice with Instant Scoring

Build confidence for Terraform interviews with practical infrastructure scenarios, architecture challenges, and debugging questions. Explore Terraform state, reusable modules, cloud provisioning, security, and deployment automation while improving your skills through concise explanations and instant scoring.

Top Terraform Interview Questions for Freshers and Experienced

50 Questions Easy · Medium · Hard

Try answering from memory, then check the reference answer and rate yourself. Your notes are optional and are not automatically graded.

Filter:

1 What problem does Terraform solve, and how does Infrastructure as Code improve infrastructure management? easy

terraforminfrastructure-as-codedeclarative
Reference answer
Terraform allows infrastructure to be defined and managed through declarative configuration files. Infrastructure as Code makes provisioning repeatable, version-controlled, and easier to review. Terraform compares the desired configuration with managed infrastructure and generates an execution plan to reconcile differences.
Did you know it?

2 What is the difference between Terraform's declarative approach and imperative infrastructure provisioning? easy

declarativeimperativeiac
Reference answer
Declarative configuration describes the desired infrastructure state without explicitly listing every provisioning step. Imperative approaches specify commands and their execution sequence. Terraform builds a dependency graph and determines the required operations from configuration, state, and provider information.
Did you know it?

3 What are the responsibilities of terraform init, plan, apply, and destroy? easy

terraform-cliworkflowcommands
Reference answer
terraform init initializes the working directory and installs required providers and modules. terraform plan previews proposed infrastructure changes without applying them. terraform apply executes an approved plan, while terraform destroy plans and removes managed resources.
Did you know it?

4 What is HashiCorp Configuration Language, and why is it used in Terraform? easy

hclconfigurationsyntax
Reference answer
HCL is a configuration language designed to express infrastructure definitions in a readable format. It supports blocks, arguments, expressions, variables, functions, and references. Terraform uses HCL to describe providers, resources, data sources, modules, and infrastructure relationships.
Did you know it?

5 How do Terraform providers differ from resources? easy

providersresourcesaws
Reference answer
Providers are plugins that implement integrations with infrastructure platforms and services. Resources represent infrastructure objects that Terraform can create, update, or delete through those providers. For example, the AWS provider exposes aws_instance to manage EC2 instances.
Did you know it?

6 What is the purpose of input variables and output values in Terraform? easy

variablesoutputsconfiguration
Reference answer
Input variables parameterize configurations so the same code can be reused across environments. Output values expose selected information from a configuration or module, such as resource identifiers and endpoints. Variables support type constraints, defaults, validation, and sensitive markings.
Did you know it?

7 What is the difference between a Terraform resource block and a data source block? easy

resourcesdata-sourcesinfrastructure
Reference answer
A resource block declares an infrastructure object managed through Terraform's lifecycle. A data source reads information from an existing system without managing that object's lifecycle. For example, aws_vpc can manage a VPC, while data.aws_vpc can retrieve details about an existing VPC.
Did you know it?

8 What is Terraform state, and why is it required even though infrastructure is already defined in configuration files? medium

terraform-stateresource-trackingstate-management
Reference answer
Terraform state records managed resource identities, attributes, and relationships between configuration addresses and real infrastructure objects. It enables Terraform to calculate changes efficiently and track resources across operations. Without appropriate state, Terraform may treat existing resources as unmanaged and attempt to create duplicates.
Did you know it?

9 How does Terraform determine the order in which infrastructure resources should be created? medium

dependency-graphdepends-onexecution-order
Reference answer
Terraform constructs a dependency graph from resource references and explicit dependencies. Resources with dependencies are processed in the required order, while independent operations may run concurrently. The depends_on argument is available when Terraform cannot infer an important dependency automatically.
Did you know it?

10 Why should Terraform configurations use provider version constraints and a dependency lock file? medium

provider-versioninglock-filereproducibility
Reference answer
Provider version constraints define which provider releases are acceptable for a configuration. The .terraform.lock.hcl file records selected provider versions and checksums to support reproducible initialization. Commit the lock file and review provider upgrades to reduce unexpected changes between developer and CI environments.
Did you know it?

11 A team stores terraform.tfstate in Git and experiences frequent merge conflicts. How would you redesign the state management process? hard

remote-statestate-lockingcollaboration
Reference answer
Move state to a shared remote backend such as an appropriately configured S3 backend or HCP Terraform. Enable supported state locking to prevent concurrent modifications and restrict state access through IAM or equivalent controls. Use encryption, versioning or recovery mechanisms, and separate state boundaries for independent environments.
Explain why state is operational data rather than a configuration file suitable for normal Git merging.
Did you know it?

12 What happens when two engineers execute terraform apply simultaneously against the same remote state? medium

state-lockingconcurrencyremote-backend
Reference answer
If the backend supports locking and it is enabled, one operation acquires the state lock while the other waits or fails to acquire it. This prevents simultaneous state writes that could cause inconsistent infrastructure tracking. State locking does not replace deployment approvals or protect against changes made outside Terraform.
Did you know it?

13 How would you recover from a Terraform state lock left behind after a failed deployment? hard

force-unlockstate-recoverytroubleshooting
Reference answer
First verify that no Terraform operation is still running against the affected state. Investigate the backend and confirm that the lock is stale before using terraform force-unlock with the correct lock ID. Never force-unlock an active operation because concurrent writes may corrupt state or produce inconsistent infrastructure.
Mention that lock recovery should follow verification of the active deployment and backend status.
Did you know it?

14 What is infrastructure drift, and how can Terraform detect changes made directly through a cloud console? medium

drift-detectionterraform-planconfiguration
Reference answer
Infrastructure drift occurs when actual infrastructure differs from Terraform's recorded or intended configuration. During normal planning, Terraform refreshes managed resource information through providers and compares it with configuration and state. Review the resulting plan to decide whether to restore the declared configuration or update the code to accept intentional changes.
Did you know it?

15 A Terraform plan unexpectedly proposes replacing a production database. What steps should be taken before applying? hard

resource-replacementproduction-safetyterraform-plan
Reference answer
Inspect the plan to identify which changed attribute requires replacement and whether it is immutable in the provider. Check configuration changes, provider upgrades, state mappings, and external infrastructure modifications. Avoid applying until the impact is understood; consider configuration corrections, state moves, or migration strategies that preserve data.
Discuss replacement indicators in Terraform plans and the importance of backups and migration planning.
Did you know it?

16 How does the lifecycle create_before_destroy argument affect resource replacement? medium

lifecyclecreate-before-destroyavailability
Reference answer
create_before_destroy requests that Terraform create a replacement resource before destroying the existing one. It can reduce downtime when the provider and infrastructure allow both resources to exist simultaneously. It may fail when unique names, quotas, or platform constraints prevent parallel resource creation.
Did you know it?

17 When is lifecycle ignore_changes appropriate, and what problems can excessive use introduce? hard

ignore-changeslifecycledrift
Reference answer
ignore_changes tells Terraform to disregard configured attribute differences during update planning for existing resources. It is useful when another authorized system controls selected attributes, such as externally managed tags. Overusing it can conceal configuration drift and prevent Terraform from correcting unintended changes.
Did you know it?

18 How does prevent_destroy protect critical infrastructure, and what are its limitations? medium

prevent-destroylifecycleresource-protection
Reference answer
The prevent_destroy lifecycle setting causes Terraform to reject plans that would destroy a protected resource while the setting remains in its configuration. It is useful for critical databases and persistent infrastructure. It does not protect against deletion outside Terraform or destruction after the resource block and its protection are removed from configuration.
Did you know it?

19 What is the difference between count and for_each when creating multiple Terraform resources? medium

countfor-eachresource-instances
Reference answer
count creates instances identified by numerical indexes, while for_each uses stable map keys or set members. Removing an item from the middle of a count-based list can shift indexes and cause unintended changes. for_each is generally preferable when resources have stable logical identifiers.
Did you know it?

20 A resource uses count with a list of server names. Removing the first name causes several resources to change. Why? hard

count-indexfor-eachresource-identity
Reference answer
count identifies instances using numeric indexes such as resource.server[0] and resource.server[1]. Removing an earlier list element shifts later values into different indexes, potentially causing updates or replacements. Use for_each with stable keys when resource identity should follow a server name rather than its list position.
Did you know it?

21 How would you design reusable Terraform modules for networking, compute, and databases across development and production? hard

terraform-modulesreusabilityenvironment-design
Reference answer
Create focused modules with explicit input variables, output contracts, and documented provider requirements. Keep environment-specific values in root configurations rather than hardcoding them inside modules. Version modules, expose only necessary customization, and avoid tightly coupling unrelated infrastructure components.
Explain how root modules compose reusable child modules while maintaining separate environment configurations.
Did you know it?

22 How can provider aliases be used to provision resources across multiple AWS regions? medium

provider-aliasmulti-regionaws
Reference answer
Define multiple AWS provider configurations using aliases for additional regions. Associate resources or modules with the required provider configuration through the provider or providers argument. For example, an aliased provider configured for us-west-2 can manage regional resources independently of the default region.
Did you know it?

23 What challenges arise when using Terraform to manage resources across multiple AWS accounts? hard

multi-accountaws-iamprovider-alias
Reference answer
Multi-account configurations require explicit credential boundaries, provider aliases, and carefully scoped IAM permissions. Cross-account resource dependencies and state ownership must be designed to avoid accidental changes in the wrong account. Use role assumption, separate deployment identities, and independent state where appropriate.
Did you know it?

24 How would you manage development, staging, and production infrastructure without accidentally applying changes to the wrong environment? hard

environment-isolationworkspacesdeployment-safety
Reference answer
Use separate root configurations or carefully managed workspaces with isolated state and environment-specific variables. Apply distinct cloud credentials, access policies, and deployment approvals for production. Validate the selected backend, workspace, account, and plan before allowing an apply operation.
Did you know it?

25 When are Terraform workspaces useful, and when should separate root configurations be preferred? medium

workspacesstate-isolationenvironments
Reference answer
CLI workspaces allow multiple state instances to share the same root configuration and backend configuration. They work well for similar environments with limited differences. Separate root configurations are often better when environments require different access boundaries, infrastructure topology, or independent release processes.
Did you know it?

26 A company wants Terraform to manage an existing manually created AWS VPC. How would you bring it under Terraform management? medium

terraform-importexisting-resourcesaws-vpc
Reference answer
Write a resource configuration that accurately describes the existing VPC and identify its cloud resource ID. Use a Terraform import block or terraform import to associate the existing object with a resource address. Run terraform plan and reconcile configuration differences before applying potentially destructive changes.
Did you know it?

27 What is the difference between a moved block and terraform state mv when refactoring resource addresses? hard

moved-blockstate-mvrefactoring
Reference answer
A moved block declares an address migration in configuration so Terraform can recognize resource renames during planning. terraform state mv directly changes resource address mappings in state. Moved blocks are preferable for reviewable, repeatable module refactoring, while direct state operations require careful coordination.
Did you know it?

28 What happens when terraform state rm is executed for a managed resource? medium

state-rmresource-trackingstate-operations
Reference answer
terraform state rm removes Terraform's tracking relationship for the selected resource without deleting the actual infrastructure object. The object remains in the cloud but is no longer managed through that state address. If its resource configuration remains, a subsequent plan may propose creating another object.
Did you know it?

29 How would you migrate Terraform state from a local backend to an S3 backend without recreating infrastructure? hard

s3-backendstate-migrationremote-state
Reference answer
Configure the S3 backend with the appropriate bucket, state key, region, access permissions, and locking strategy. Run terraform init -migrate-state and follow the migration prompts after taking a verified backup. Confirm that the remote state contains the expected resource mappings and that subsequent plans do not propose unintended changes.
Did you know it?

30 How should sensitive credentials be handled in Terraform variables, outputs, and state files? hard

sensitive-valuessecrets-managementstate-security
Reference answer
Mark sensitive inputs and outputs appropriately to reduce accidental disclosure in CLI output. Remember that sensitive values can still be stored in state and plan files, so protect backend access and encryption. Prefer short-lived credentials, secret managers, and supported ephemeral or write-only mechanisms when available.
Highlight that sensitive = true does not automatically encrypt or remove secret values from Terraform state.
Did you know it?

31 How can Terraform use AWS IAM roles instead of storing permanent access keys in configuration files? medium

iam-rolesaws-providercredential-security
Reference answer
Configure the AWS provider to use credentials supplied through an IAM role, workload identity, or an approved credential chain. For cross-account operations, use assume_role with an appropriately trusted role. Short-lived credentials reduce the risk associated with long-lived access keys committed to repositories or stored in CI systems.
Did you know it?

32 What is the purpose of terraform validate, fmt, and test in a Terraform development workflow? medium

terraform-testvalidationcode-quality
Reference answer
terraform fmt standardizes configuration formatting, while terraform validate checks configuration syntax and internal consistency. terraform test executes Terraform test files to verify infrastructure behavior through supported assertions and test runs. These commands complement, but do not replace, provider-aware planning, security scanning, and integration testing.
Did you know it?

33 How would you build a secure CI/CD pipeline for Terraform infrastructure changes? hard

terraform-cicdsecurity-scanningdeployment-automation
Reference answer
Run formatting, validation, security checks, and terraform plan for every proposed infrastructure change. Publish the plan for review and require approval before production deployment. Use short-lived cloud credentials, restricted backend permissions, state locking, and serialized apply operations. Apply a saved plan when appropriate to ensure the reviewed changes match the deployment.
Explain how approval gates, credential isolation, and saved plans reduce production deployment risks.
Did you know it?

34 Why can running terraform plan in one pipeline stage and terraform apply without a saved plan in another stage be risky? hard

saved-plancicddeployment-consistency
Reference answer
A fresh apply recalculates the plan, so changed configuration, variables, provider selections, or infrastructure state may produce different actions. Saving a plan with terraform plan -out and applying that file preserves the reviewed operation set. Saved plans contain potentially sensitive information and must be secured and used against the intended state.
Did you know it?

35 How can Terraform preconditions, postconditions, and check blocks improve infrastructure validation? hard

preconditionspostconditionscheck-blocks
Reference answer
Preconditions validate assumptions before relevant resource operations, while postconditions verify conditions after resource evaluation. Check blocks support assertions about infrastructure health and configuration expectations. Failed preconditions or postconditions can block operations, whereas failed check assertions generally produce warnings rather than stopping the run.
Did you know it?

36 How would you enforce infrastructure security policies such as prohibiting publicly accessible storage buckets? hard

policy-as-codeopacloud-security
Reference answer
Use policy-as-code tooling such as Sentinel, OPA, or suitable infrastructure security scanners in the delivery pipeline. Evaluate Terraform configuration or plan data against organizational security rules before applying changes. Combine policy checks with cloud IAM restrictions and preventive organization-level controls for stronger enforcement.
Did you know it?

37 A Terraform apply fails after successfully creating several resources. What happens during the next apply? hard

partial-applyfailure-recoverystate-consistency
Reference answer
Terraform does not automatically roll back all previously completed infrastructure operations when an apply fails. Successfully recorded changes normally remain in state, while partially completed or failed operations require reconciliation. The next plan refreshes managed objects and determines the remaining changes needed to reach the desired configuration.
Did you know it?

38 How can you troubleshoot a Terraform plan that reports an unknown value for a resource attribute? hard

unknown-valuesexpression-evaluationterraform-plan
Reference answer
Terraform represents values as unknown when they depend on information that becomes available only during apply. Trace references and dependencies to identify the resource producing the computed value. Avoid using apply-time unknown values as for_each keys or count expressions, which must be known during planning.
Did you know it?

39 Why does Terraform reject a for_each expression when its keys depend on resource IDs generated during apply? hard

for-eachunknown-valuesresource-addressing
Reference answer
Terraform must know resource instance addresses before it can construct the execution plan. Resource IDs generated during apply cannot reliably determine for_each keys during planning. Use stable configuration-defined keys and place computed IDs in map values instead of keys.
Provide an example using a map keyed by logical resource names rather than cloud-generated IDs.
Did you know it?

40 What is the difference between local values and input variables, and when should each be used? medium

localsinput-variablesexpressions
Reference answer
Input variables accept values from callers, environment variables, variable files, or defaults. Local values define named expressions within a module and cannot be overridden directly by callers. Use variables for configurable inputs and locals for derived values, naming conventions, and repeated expressions.
Did you know it?

41 How can dynamic blocks reduce repeated nested configuration, and when should they be avoided? medium

dynamic-blockshclconfiguration-reuse
Reference answer
Dynamic blocks generate repeated nested blocks from collections using for_each expressions. They are useful when a provider resource requires multiple similar nested configurations. Avoid excessive dynamic nesting when ordinary resource blocks or simpler expressions would make the configuration easier to understand.
Did you know it?

42 How would you handle infrastructure dependencies that span two independent Terraform state files? hard

remote-statecross-stackdependencies
Reference answer
Expose stable outputs from the producing configuration and consume them through an appropriate data source or published service interface. terraform_remote_state can retrieve root outputs when backend access is available, but it also requires access to the state snapshot. Prefer dedicated configuration stores or cloud data sources when consumers should not receive broad state access.
Did you know it?

43 What are the risks of using null_resource and provisioners for application deployment or infrastructure configuration? hard

provisionersnull-resourceconfiguration-management
Reference answer
Provisioners introduce imperative operations that are harder for Terraform to model, retry, and track reliably. Their side effects may not be represented accurately in state, complicating drift detection and recovery. Prefer cloud-init, immutable images, configuration management, or dedicated deployment tools for application configuration.
Did you know it?

44 How would you implement a zero-downtime infrastructure migration from an existing EC2 instance to a replacement instance? hard

zero-downtimeec2infrastructure-migration
Reference answer
Provision the replacement instance alongside the existing one and validate its health before switching traffic. Use load balancer target registration, rolling deployment strategies, or controlled DNS changes as appropriate. Separate persistent data from disposable compute resources and plan rollback before destroying the old instance.
Did you know it?

45 How can Terraform execution performance be improved when managing thousands of cloud resources? hard

terraform-performanceparallelismlarge-scale-iac
Reference answer
Measure provider API latency, state refresh time, dependency graph constraints, and resource operation concurrency. Split infrastructure into independently managed state boundaries when ownership and dependencies justify it. Tune parallelism cautiously, reduce unnecessary data lookups, and avoid exceeding provider API rate limits.
Did you know it?

46 Why can increasing Terraform's parallelism setting make an infrastructure deployment slower or less reliable? hard

parallelismapi-throttlingperformance-tuning
Reference answer
Higher parallelism allows more independent operations to execute concurrently but can overwhelm provider APIs or backend services. Cloud rate limits may cause throttling, retries, and increased execution time. Select parallelism based on observed API limits, dependency characteristics, and deployment stability rather than maximizing concurrency.
Did you know it?

47 How would you troubleshoot a Terraform deployment that repeatedly fails with cloud API rate-limit errors? medium

api-rate-limitsprovider-errorstroubleshooting
Reference answer
Inspect provider diagnostics and cloud API responses to identify throttled operations. Reduce Terraform parallelism, review provider retry behavior, and distribute independent deployments where appropriate. Avoid repeated uncontrolled retries, and coordinate deployments that share the same account-level service quotas.
Did you know it?

48 How would you design disaster recovery for Terraform state stored in a remote backend? hard

disaster-recoverystate-backupremote-backend
Reference answer
Enable appropriate backend encryption, access controls, versioning, and recovery capabilities. Maintain a documented recovery process that identifies the correct state version and verifies infrastructure consistency before restoration. Test recovery procedures periodically and protect backups from accidental deletion or unauthorized modification.
Explain why restoring an old state snapshot without reconciling current infrastructure can create dangerous plans.
Did you know it?

49 A developer changes the Terraform module source version, and the next plan proposes replacing several resources. How would you investigate? hard

module-versioningresource-replacementupgrade-strategy
Reference answer
Compare module versions for changes to resource addresses, immutable arguments, provider requirements, and default values. Review the plan to distinguish actual infrastructure changes from address refactoring. Use moved blocks for compatible address migrations and test module upgrades in a non-production environment before rollout.
Did you know it?

50 How would you design an enterprise Terraform platform supporting multiple teams, cloud accounts, environments, and controlled production deployments? hard

enterprise-architectureterraform-governanceplatform-engineering
Reference answer
Establish reusable versioned modules, clear infrastructure ownership, isolated state boundaries, and standardized provider configurations. Use federated identities, least-privilege permissions, encrypted remote state, locking, and policy-as-code enforcement. Automate validation, security scanning, reviewed plans, approval gates, and controlled applies through CI/CD. Add drift monitoring, audit trails, cost visibility, disaster recovery procedures, and module lifecycle governance.
Organize the answer around module governance, state isolation, access control, deployment safety, operational visibility, and recovery.
Did you know it?
0 / 0 answered

↑ Back to top