Terraform commands are essential skills for DevOps engineers, cloud engineers, platform engineers, and Site Reliability Engineers who manage infrastructure as code. Professionals at this level are expected to understand Terraform workflow commands such as initialization, validation, formatting, planning, deployment, and resource lifecycle management to automate and maintain reliable cloud infrastructure.
Most Asked Terraform Commands Interview Questions
- What is the purpose of
terraform init? - What is the difference between
terraform planandterraform apply? - What does
terraform validatecheck? - How does
terraform importwork? - What happens when
terraform destroyis executed? - Why is
terraform fmtimportant in Terraform projects? - How are Terraform commands used in CI/CD pipelines?
Beginner Terraform Commands Interview Questions and Answers
Terraform Init Interview Questions
What is the purpose of terraform init?
terraform init initializes a Terraform working directory by downloading required providers, configuring backend settings, and preparing modules. It is the first command executed after creating or cloning a Terraform project because it installs dependencies and prepares Terraform configuration files for planning and deployment operations.
The command creates the .terraform directory, downloads provider plugins based on the Terraform configuration, and initializes modules. It also configures remote state backends such as Amazon S3, Azure Storage, or Google Cloud Storage.
Example:
terraform init
A typical Terraform workflow begins with:
terraform init
terraform validate
terraform plan
terraform apply
Terraform initialization ensures that the required provider plugins and backend configurations are available before infrastructure provisioning begins.
What happens internally when terraform init is executed?
When terraform init runs, Terraform analyzes configuration files, identifies required providers and modules, downloads dependencies, and configures the backend for state management. It prepares the local environment required for executing future Terraform commands.
The initialization process performs several tasks:
- Loads Terraform configuration files:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
- Downloads provider plugins:
.terraform/
└── providers/
- Initializes modules:
terraform init
- Configures backend storage:
terraform {
backend "s3" {
bucket = "terraform-state-storage"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
This process enables Terraform dependency management and remote state operations.
Does terraform init create infrastructure?
terraform init does not create or modify cloud infrastructure. It only prepares the Terraform environment by installing providers, downloading modules, and configuring state backends required for later operations.
Infrastructure creation happens only when commands such as terraform apply are executed.
Example workflow:
terraform init # Prepare Terraform
terraform plan # Preview changes
terraform apply # Create resources
Because initialization is a non-destructive operation, it is safe to run multiple times during development and deployment processes.
What files and folders are generated after running terraform init?
After executing terraform init, Terraform creates supporting files and directories used for managing dependencies and state operations. The primary generated directory is .terraform.
Example structure:
project/
│
├── main.tf
├── variables.tf
├── outputs.tf
└── .terraform/
└── providers/
The .terraform.lock.hcl file may also be created to record provider versions:
.terraform.lock.hcl
This dependency lock file ensures consistent provider versions across development environments and CI/CD pipelines.
What is the .terraform directory?
The .terraform directory stores Terraform-generated files required for executing infrastructure operations. It contains downloaded provider plugins, module information, and backend metadata.
Example:
.terraform/
├── providers/
└── modules/
The directory is automatically recreated when running:
terraform init
Teams usually exclude this directory from version control because it contains locally generated dependencies.
Example .gitignore:
.terraform/
Terraform uses this directory to locate provider binaries and module dependencies during execution.
Why should terraform init be executed before other Terraform commands?
terraform init must be executed before most Terraform commands because it prepares the working directory and installs required dependencies. Without initialization, Terraform cannot locate providers, modules, or backend configurations.
For example, running:
terraform plan
before initialization results in an error:
Error: Inconsistent dependency lock file
The recommended workflow is:
git clone terraform-project
cd terraform-project
terraform init
terraform plan
terraform apply
This ensures the Terraform environment is ready for infrastructure management.
What happens if you run terraform init multiple times?
Running terraform init multiple times is safe because Terraform checks existing dependencies and only downloads or updates required components. It is commonly executed whenever provider versions, modules, or backend configurations change.
Example:
terraform init
terraform init
Terraform detects existing initialization and displays:
Terraform has been successfully initialized!
Using:
terraform init -upgrade
forces Terraform to check for newer compatible provider and module versions.
How do you initialize Terraform with a remote backend?
Terraform remote backends store state files outside the local machine, enabling collaboration and state locking. Remote backend configuration is initialized using terraform init.
Example AWS S3 backend:
terraform {
backend "s3" {
bucket = "company-terraform-state"
key = "production/state.tfstate"
region = "us-east-1"
}
}
Initialize:
terraform init
Terraform connects to the configured backend and migrates existing state if required.
Remote backends improve security, collaboration, and state management in enterprise Terraform environments.
What is the purpose of the -upgrade option in terraform init?
The -upgrade option updates Terraform providers and modules to the newest versions allowed by configuration constraints. It is useful when teams want to refresh dependencies without manually deleting Terraform files.
Example:
terraform init -upgrade
Given:
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
Terraform downloads the latest compatible AWS provider version.
This command is commonly used during provider upgrades, security patching, and infrastructure maintenance.
What is the difference between terraform init and terraform get?
terraform init is the modern command used to initialize Terraform projects, configure backends, install providers, and download modules. terraform get was primarily used in older Terraform versions to download modules only.
Modern workflow:
terraform init
Legacy workflow:
terraform get
terraform init replaces the need for terraform get by combining module installation with provider and backend initialization.
Terraform Validate Interview Questions
What is terraform validate?
terraform validate checks whether Terraform configuration files are syntactically valid and internally consistent. It verifies configuration structure, resource definitions, provider references, and Terraform language usage without creating or modifying infrastructure.
Example:
terraform validate
Successful output:
Success! The configuration is valid.
It is commonly executed in CI/CD pipelines before running terraform plan to catch configuration errors early.
What types of errors can terraform validate detect?
terraform validate detects configuration-related problems such as invalid syntax, missing arguments, incorrect resource blocks, and invalid Terraform expressions.
Example invalid configuration:
resource "aws_instance" {
ami = "abc"
}
Validation detects:
Missing required argument
However, it does not verify whether cloud resources exist or whether credentials are valid.
Terraform validation focuses on configuration correctness rather than infrastructure state.
Does terraform validate check cloud resources?
No, terraform validate does not communicate with cloud providers or inspect existing infrastructure. It only analyzes Terraform configuration files locally.
For example:
terraform validate
does not check:
- AWS account permissions
- Azure subscriptions
- GCP projects
- Existing cloud resources
For provider connectivity and infrastructure changes, use:
terraform plan
Validation is designed as a fast configuration quality check.
What is the difference between terraform validate and terraform plan?
terraform validate checks Terraform configuration syntax and structure, while terraform plan compares configuration with real infrastructure and generates an execution plan.
Comparison:
| Command | Purpose |
|---|---|
| terraform validate | Checks configuration correctness |
| terraform plan | Calculates infrastructure changes |
Example:
terraform validate
terraform plan
A configuration can pass validation but still fail during planning due to authentication issues, missing resources, or provider errors.
Why is terraform validate commonly used in CI/CD pipelines?
terraform validate provides an automated quality gate that prevents invalid Terraform configurations from reaching deployment stages. It helps teams detect syntax issues early during pull requests.
Example GitHub Actions workflow:
- name: Terraform Validate
run: terraform validate
Combined with:
terraform fmt -check
terraform validate
terraform plan
it improves infrastructure code quality and deployment reliability.
Can terraform validate detect provider authentication errors?
No, terraform validate does not authenticate with cloud providers or verify credentials. It validates Terraform configuration locally.
Example:
terraform validate
may succeed even if:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
are missing.
Authentication-related issues are detected during:
terraform plan
or:
terraform apply
because those commands interact with cloud APIs.
Terraform Fmt Interview Questions
What is the purpose of terraform fmt?
terraform fmt automatically formats Terraform configuration files according to HashiCorp's standard formatting rules. It improves readability, consistency, and maintainability across Terraform projects.
Example:
terraform fmt
Before formatting:
resource "aws_instance"{
ami="abc"
}
After formatting:
resource "aws_instance" {
ami = "abc"
}
Teams use it to maintain clean Infrastructure as Code repositories.
Why is formatting important in Terraform projects?
Terraform formatting improves collaboration by ensuring all engineers follow the same coding style. Consistent formatting makes configuration reviews easier and reduces unnecessary differences in version control systems.
Common benefits:
- Better code readability
- Cleaner pull requests
- Easier troubleshooting
- Standardized Terraform modules
Example:
terraform fmt -recursive
formats Terraform files inside nested module directories.
What does the -check flag do in terraform fmt?
The -check option verifies whether Terraform files are properly formatted without modifying them. It is commonly used in CI/CD pipelines.
Example:
terraform fmt -check
If files require formatting:
main.tf
variables.tf
The pipeline can fail and require developers to run:
terraform fmt
This enforces Terraform style standards automatically.
What is the difference between terraform fmt and terraform validate?
terraform fmt formats Terraform configuration files, while terraform validate checks whether the configuration is syntactically correct.
Comparison:
| Command | Function |
|---|---|
| terraform fmt | Code formatting |
| terraform validate | Configuration validation |
Example workflow:
terraform fmt
terraform validate
terraform plan
Formatting improves readability, while validation ensures Terraform can understand the configuration.
Can terraform fmt modify Terraform logic?
No, terraform fmt only changes formatting and whitespace. It does not modify resource definitions, variables, dependencies, or infrastructure logic.
Example:
Before:
variable "region"{type="string"}
After:
variable "region" {
type = "string"
}
The Terraform behavior remains identical.
How is terraform fmt used in GitHub Actions or Jenkins pipelines?
terraform fmt is commonly included as a validation step before merging Terraform code. It ensures infrastructure code follows formatting standards.
Example CI command:
terraform fmt -check -recursive
terraform validate
terraform plan
A failed formatting check prevents inconsistent Terraform code from entering production branches and improves Infrastructure as Code governance.
Intermediate Terraform Commands Interview Questions and Answers
Terraform Plan Interview Questions
What is terraform plan?
terraform plan creates an execution preview that shows the changes Terraform will make to infrastructure without applying them. It compares the current Terraform state with configuration files and real-world infrastructure to determine resources that need to be created, updated, or removed.
Example:
terraform plan
Terraform generates an execution plan containing resource actions:
+ create
~ update
- destroy
The command is a critical part of Infrastructure as Code workflows because it allows DevOps teams to review changes before deployment.
What information does terraform plan display?
terraform plan displays the proposed infrastructure changes based on the current Terraform configuration, state file, and provider APIs. It shows resources that Terraform intends to create, modify, or destroy.
Example output:
Terraform will perform the following actions:
# aws_instance.web will be created
+ resource "aws_instance" "web" {
+ ami = "ami-123456"
}
The plan includes:
- Resource lifecycle changes
- Attribute modifications
- Dependency ordering
- Replacement operations
This visibility helps engineers perform infrastructure change reviews before production deployments.
What is Terraform's execution plan?
A Terraform execution plan is a generated preview of infrastructure modifications that Terraform calculates before applying changes. It represents the desired transition from the current infrastructure state to the configuration-defined state.
Example workflow:
terraform plan -out=tfplan
The saved plan file can later be applied:
terraform apply tfplan
Execution plans improve deployment safety by allowing teams to validate infrastructure changes, detect unexpected modifications, and implement approval-based workflows.
What is the difference between terraform plan and terraform apply?
terraform plan only previews infrastructure changes, while terraform apply executes those changes against cloud providers. The plan command is read-only, whereas apply creates, updates, or deletes resources.
Comparison:
| Command | Purpose |
|---|---|
| terraform plan | Preview changes |
| terraform apply | Execute changes |
Example:
terraform plan
terraform apply
A common enterprise workflow requires engineers to review and approve the Terraform plan before running apply in production environments.
What do the symbols (+, -, ~) represent in a Terraform plan?
Terraform plan symbols indicate the lifecycle actions Terraform will perform on resources.
Common symbols:
| Symbol | Meaning |
|---|---|
| + | Create resource |
| - | Destroy resource |
| ~ | Modify existing resource |
| +/- | Replace resource |
Example:
+ aws_instance.web
~ aws_security_group.app
-/+ aws_database.instance
Understanding these symbols helps DevOps engineers identify whether Terraform will provision new infrastructure, update existing components, or replace resources.
How can you save a Terraform execution plan?
Terraform allows engineers to save a generated plan into a file using the -out option. Saved plans ensure that the exact reviewed changes are applied later without recalculating infrastructure differences.
Example:
terraform plan -out=production.tfplan
Apply the saved plan:
terraform apply production.tfplan
Saved plans are commonly used in enterprise CI/CD pipelines where infrastructure changes require approval before deployment.
What is the purpose of the -out option in terraform plan?
The -out option stores Terraform's generated execution plan as a binary plan file. This allows teams to separate the planning phase from the deployment phase.
Example:
terraform plan -out=myplan
Later:
terraform apply myplan
Benefits include:
- Approval-based deployments
- Consistent deployments
- Reduced configuration drift between review and execution
The saved plan contains the exact resource actions Terraform calculated.
What is the difference between speculative and saved plans?
A speculative plan is generated for review purposes and is not intended for direct application, while a saved plan is stored and can be executed later using terraform apply.
Speculative plan:
terraform plan
Saved plan:
terraform plan -out=tfplan
Speculative plans are commonly used in pull requests, while saved plans are used in controlled production deployment workflows.
How does Terraform determine resource changes?
Terraform determines resource changes by comparing three sources:
- Terraform configuration files
- Terraform state file
- Current infrastructure information from providers
Example:
resource "aws_instance" "server" {
instance_type = "t3.micro"
}
Terraform checks whether the actual AWS instance matches the desired configuration.
The process involves:
- Reading state
- Refreshing resource information
- Calculating differences
- Generating an execution plan
This comparison process helps Terraform maintain infrastructure consistency.
Can terraform plan modify infrastructure?
No, terraform plan does not create, update, or delete infrastructure resources. It only performs a comparison and displays the changes Terraform would make.
Example:
terraform plan
Safe operations:
- Reading Terraform state
- Querying provider APIs
- Calculating changes
Actual modifications require:
terraform apply
Because it does not change infrastructure, terraform plan is commonly used as a safe review step before deployments.
What happens if infrastructure changes outside Terraform before running plan?
When infrastructure is manually modified outside Terraform, Terraform detects configuration drift during the planning phase. It compares the actual resource state with the stored Terraform state and desired configuration.
Example:
An AWS instance size is manually changed:
Terraform state:
t3.micro
AWS console:
t3.large
Running:
terraform plan
shows the difference:
~ instance_type = "t3.large" -> "t3.micro"
Terraform helps teams identify and correct infrastructure drift.
How do variables affect terraform plan?
Terraform variables influence the values used during execution planning. Different variable values can produce different infrastructure changes without modifying Terraform configuration files.
Example:
variables.tf
variable "instance_type" {
default = "t3.micro"
}
Using a custom value:
terraform plan -var="instance_type=t3.medium"
Terraform generates a plan based on the supplied variable value.
Variables enable reusable Terraform modules and environment-specific infrastructure configurations.
How can you review infrastructure changes before deployment?
Infrastructure changes can be reviewed by running terraform plan and analyzing the generated execution plan. Teams commonly use saved plans and CI/CD approval workflows for production deployments.
Example:
terraform plan -out=review.tfplan
Review:
terraform show review.tfplan
Typical review process:
- Developer submits Terraform changes
- CI runs validation and plan
- Team reviews changes
- Approved plan is applied
This approach improves infrastructure security and governance.
What is the purpose of terraform plan -destroy?
terraform plan -destroy creates a preview of resources that would be removed if a destroy operation is executed. It allows engineers to review deletion actions before actually removing infrastructure.
Example:
terraform plan -destroy
Output:
- aws_instance.web will be destroyed
- aws_vpc.main will be destroyed
This command is useful for disaster recovery testing, environment cleanup, and preventing accidental deletion of production resources.
What is the difference between terraform plan and terraform plan -refresh-only?
terraform plan calculates infrastructure changes required to match configuration, while terraform plan -refresh-only only updates Terraform state information without proposing configuration changes.
Example:
terraform plan -refresh-only
Use cases:
- Detecting manual infrastructure changes
- Updating state records
- Auditing infrastructure
refresh-only mode is useful when teams need to synchronize state without modifying cloud resources.
How does Terraform handle dependencies during planning?
Terraform analyzes resource relationships and creates a dependency graph before generating a plan. It determines the correct order for resource creation, modification, and deletion.
Example:
resource "aws_instance" "web" {
subnet_id = aws_subnet.main.id
}
Terraform understands:
VPC
↓
Subnet
↓
EC2 Instance
The dependency graph ensures resources are managed in the correct sequence during deployment.
How does terraform plan help in production deployments?
terraform plan improves production deployment safety by providing visibility into infrastructure changes before execution. It enables teams to identify unexpected resource replacements, security changes, and configuration mistakes.
Production workflow:
terraform init
terraform validate
terraform plan -out=prod.tfplan
terraform apply prod.tfplan
Benefits:
- Change approval
- Auditability
- Reduced deployment risks
- Better infrastructure governance
Terraform planning is a core practice in mature DevOps and platform engineering environments.
Terraform Apply Interview Questions
What is terraform apply?
terraform apply executes the changes defined in Terraform configuration files and applies the generated execution plan to real infrastructure. It creates new resources, updates existing resources, and removes resources when required to make the actual environment match the desired Terraform configuration.
Example:
terraform apply
Terraform communicates with cloud providers through provider plugins and performs resource lifecycle operations based on the dependency graph. It is the command responsible for actual infrastructure provisioning and modification.
What happens during terraform apply?
During terraform apply, Terraform evaluates configuration files, refreshes the current state, creates an execution plan, requests confirmation, and performs infrastructure changes through provider APIs.
The workflow includes:
Configuration
|
v
Terraform State
|
v
Execution Plan
|
v
Cloud Provider API
|
v
Infrastructure Changes
Example:
terraform apply
Terraform then performs actions such as:
- Creating virtual machines
- Updating networking resources
- Managing IAM policies
- Modifying cloud services
After successful execution, Terraform updates the state file with the latest resource information.
How does Terraform determine the order of resource creation?
Terraform determines resource creation order by building a dependency graph from resource references, explicit dependencies, and provider requirements. Resources with dependencies are created only after their required components are available.
Example:
resource "aws_instance" "web" {
subnet_id = aws_subnet.application.id
}
Terraform understands:
VPC
|
Subnet
|
EC2 Instance
During terraform apply, Terraform automatically creates resources in the correct sequence. This dependency management prevents failures caused by creating dependent resources too early.
What is the purpose of the -auto-approve option in terraform apply?
The -auto-approve option skips Terraform's interactive confirmation prompt and immediately applies infrastructure changes. It is commonly used in automated CI/CD pipelines where manual approval is handled by external workflow systems.
Example:
terraform apply -auto-approve
Normal execution:
Do you want to perform these actions?
Only 'yes' will be accepted.
With -auto-approve, Terraform proceeds automatically.
Although useful for automation, teams should carefully control its usage in production environments because it removes manual confirmation.
What is the difference between applying directly and applying a saved plan?
Applying directly allows Terraform to generate a new plan before deployment, while applying a saved plan executes a previously reviewed plan file without recalculating changes.
Direct apply:
terraform apply
Saved plan workflow:
terraform plan -out=production.tfplan
terraform apply production.tfplan
Saved plans are preferred in enterprise environments because they support approval workflows. The exact changes reviewed by engineers are the same changes deployed to infrastructure.
How does terraform apply handle dependencies?
terraform apply uses Terraform's dependency graph to determine the correct order for creating, updating, and deleting resources. Terraform automatically identifies relationships between resources through references and dependency declarations.
Example:
resource "aws_instance" "app" {
security_groups = [
aws_security_group.web.id
]
}
Dependency graph:
Security Group
|
v
EC2 Instance
Terraform applies changes efficiently by creating independent resources in parallel while respecting required dependencies.
What happens if terraform apply fails midway?
If terraform apply fails during execution, Terraform records successful changes in the state file and leaves unsuccessful resources for future operations. Terraform does not automatically roll back completed infrastructure changes.
Example:
Resource A created successfully
Resource B failed
Resource C not started
After fixing the issue:
terraform apply
Terraform detects the current state and continues from the remaining changes.
Common causes of failure include:
- Permission errors
- Resource limits
- Invalid configurations
- Provider API failures
Can terraform apply update existing resources?
Yes, terraform apply can update existing resources when Terraform detects differences between the current infrastructure state and the desired configuration. The update behavior depends on whether the provider supports in-place modification or requires resource replacement.
Example:
Before:
instance_type = "t3.micro"
After:
instance_type = "t3.medium"
Terraform plan:
~ aws_instance.web
Terraform then applies the required modification:
terraform apply
Some changes occur without downtime, while others require resource recreation.
How can you target a specific resource using terraform apply?
Terraform allows targeting specific resources using the -target option. This restricts Terraform operations to selected resources instead of applying all pending infrastructure changes.
Example:
terraform apply -target=aws_instance.web
Targeting is useful for:
- Debugging failed deployments
- Recovering specific resources
- Performing controlled changes
However, HashiCorp recommends avoiding frequent use because it can bypass Terraform's normal dependency management and create configuration drift.
What is the difference between terraform apply and terraform apply -refresh-only?
terraform apply modifies infrastructure to match the Terraform configuration, while terraform apply -refresh-only updates the Terraform state file without changing actual resources.
Normal apply:
terraform apply
Refresh-only apply:
terraform apply -refresh-only
Refresh-only mode is useful when:
- Resources were manually changed
- Teams want updated state information
- No infrastructure modification is required
It helps synchronize Terraform state with existing infrastructure safely.
How does Terraform update the state file after terraform apply?
After successful resource operations, Terraform updates the state file with the latest infrastructure information. The state file stores resource IDs, attributes, dependencies, and metadata required for future planning operations.
Example:
terraform.tfstate
State update process:
Apply Changes
|
v
Provider Response
|
v
Update Terraform State
Remote backends such as:
- Amazon S3
- Azure Storage
- Google Cloud Storage
store state centrally and support team collaboration with state locking.
What happens when you run terraform apply without running terraform plan?
When terraform apply runs without a saved plan, Terraform automatically creates a new execution plan, displays the proposed changes, and requests confirmation before applying them.
Example:
terraform apply
Workflow:
terraform apply
|
v
Generate Plan
|
v
Approve Changes
|
v
Apply Infrastructure
In production environments, teams often separate these steps:
terraform plan -out=planfile
terraform apply planfile
This provides better control and approval management.
What permissions are required for terraform apply?
terraform apply requires permissions that allow Terraform providers to create, modify, and delete infrastructure resources. The exact permissions depend on the cloud provider and resources being managed.
Examples:
AWS permissions:
ec2:CreateInstance
ec2:TerminateInstances
iam:CreateRole
Azure permissions:
Microsoft.Compute/*
Microsoft.Network/*
Terraform uses configured credentials such as:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
Proper IAM permissions and least-privilege policies are important for secure Terraform deployments.
How do you safely use terraform apply in production environments?
Safe production usage of terraform apply requires review processes, remote state management, access controls, and automated validation steps.
Recommended workflow:
terraform fmt -check
terraform validate
terraform plan -out=prod.tfplan
terraform apply prod.tfplan
Enterprise best practices include:
- Pull request approvals
- Remote state storage
- State locking
- Limited production permissions
- Deployment auditing
These practices reduce accidental infrastructure changes and improve operational reliability.
What is the difference between terraform apply and terraform destroy?
terraform apply creates or updates infrastructure to match the Terraform configuration, while terraform destroy removes Terraform-managed resources.
Comparison:
| Command | Purpose |
|---|---|
| terraform apply | Provision/update resources |
| terraform destroy | Delete resources |
Example:
Create:
terraform apply
Remove:
terraform destroy
Both commands use Terraform state information to identify managed resources and communicate with cloud provider APIs.
How does terraform apply handle resource replacement?
When a resource attribute cannot be updated in place, Terraform destroys the existing resource and creates a replacement. The plan output identifies these operations before apply execution.
Example:
-/+ aws_instance.web
Meaning:
- Destroy old resource
+ Create new resource
Replacement scenarios may include:
- Changing immutable properties
- Changing resource identifiers
- Provider-specific limitations
Engineers should carefully review replacement operations because they may cause downtime.
What happens if someone manually changes infrastructure after terraform apply?
Manual changes create infrastructure drift because the actual environment no longer matches Terraform configuration and state. Terraform detects these differences during future planning operations.
Example:
Terraform configuration:
instance_type = "t3.micro"
Manual AWS console change:
instance_type = "t3.large"
Running:
terraform plan
shows:
~ instance_type: t3.large -> t3.micro
Terraform helps restore infrastructure consistency by applying the declared configuration.
Advanced Terraform Commands Interview Questions and Answers
Terraform Destroy Interview Questions
What is terraform destroy?
terraform destroy removes all infrastructure resources managed by Terraform in the current working directory. It reads the Terraform state file, identifies tracked resources, and sends deletion requests to the appropriate cloud provider APIs.
Example:
terraform destroy
Terraform first creates a destroy execution plan and asks for confirmation before deleting resources. It is commonly used for temporary environments, testing infrastructure, and controlled resource cleanup.
What happens internally during terraform destroy?
During terraform destroy, Terraform evaluates the state file, creates a destruction plan, determines resource dependencies, and removes resources in the correct order.
Execution flow:
Terraform Configuration
|
v
Terraform State File
|
v
Destroy Plan
|
v
Cloud Provider APIs
|
v
Resource Deletion
Example:
terraform destroy
Terraform removes managed resources such as:
- Virtual machines
- Networks
- Storage resources
- Databases
- Security configurations
After successful completion, Terraform updates the state file to remove deleted resources.
How does Terraform determine the deletion order?
Terraform determines deletion order using its dependency graph. Resources that depend on other resources are destroyed before the resources they depend on.
Example:
resource "aws_instance" "app" {
subnet_id = aws_subnet.main.id
}
Dependency relationship:
EC2 Instance
|
v
Subnet
|
v
VPC
During destruction:
Delete EC2 Instance
|
v
Delete Subnet
|
v
Delete VPC
This dependency-aware deletion prevents failures caused by removing required resources too early.
Can you destroy a single resource using Terraform?
Yes, Terraform allows targeting specific resources during destruction using the -target option. This removes only the selected resource instead of destroying the entire Terraform-managed infrastructure.
Example:
terraform destroy -target=aws_instance.web
Terraform removes only:
aws_instance.web
Targeted destruction is useful for troubleshooting and controlled cleanup, but it should be used carefully because it can bypass Terraform's normal dependency management.
What is the difference between terraform destroy and manually deleting cloud resources?
terraform destroy removes resources through Terraform while updating the Terraform state file. Manual deletion through cloud consoles removes resources without updating Terraform state automatically.
Terraform-managed deletion:
terraform destroy
Manual deletion:
AWS Console → Delete Resource
Manual deletion can create:
- State inconsistencies
- Drift
- Failed future plans
Terraform destroy maintains synchronization between infrastructure and Terraform state.
What precautions should be taken before running terraform destroy?
Before executing terraform destroy, engineers should review the deletion plan, verify the target environment, and confirm that important data is backed up.
Recommended steps:
terraform plan -destroy
Review:
- Resources being deleted
- Production impact
- Database dependencies
- Backup availability
Additional precautions:
- Use remote state backups
- Require approval for production deletion
- Verify workspace selection
- Avoid running from incorrect directories
How do you preview destruction before running terraform destroy?
Terraform provides terraform plan -destroy to preview which resources will be removed without actually deleting them.
Example:
terraform plan -destroy
Output:
Plan: 0 to add, 0 to change, 15 to destroy.
This allows engineers to review deletion operations before execution.
Production workflows commonly use:
terraform plan -destroy -out=destroy.tfplan
followed by an approval process.
What is the difference between terraform destroy and terraform plan -destroy?
terraform plan -destroy only shows the resources Terraform would remove, while terraform destroy actually performs the deletion.
Comparison:
| Command | Purpose |
|---|---|
| terraform plan -destroy | Preview deletion |
| terraform destroy | Execute deletion |
Example:
Preview:
terraform plan -destroy
Delete:
terraform destroy
Using the planning command first reduces accidental infrastructure removal.
How can you prevent accidental execution of terraform destroy?
Organizations prevent accidental destruction using access controls, approval workflows, and Terraform configuration protections.
Common approaches:
- Require deployment approvals
- Restrict production credentials
- Use policy-as-code tools
- Enable resource deletion protection
Example AWS resource protection:
resource "aws_db_instance" "database" {
deletion_protection = true
}
Teams also separate environments using Terraform workspaces and remote state isolation.
What happens to the Terraform state file after destroy?
After successful destruction, Terraform updates the state file by removing information about deleted resources. The state file remains but no longer tracks destroyed infrastructure.
Before:
terraform.tfstate
aws_instance.web
aws_vpc.main
After:
terraform.tfstate
{}
Remote backends continue storing the updated state version for auditing and collaboration.
Terraform Import Interview Questions
What is terraform import?
terraform import brings existing infrastructure resources under Terraform management by adding them to the Terraform state file. It allows teams to manage manually created cloud resources using Infrastructure as Code without recreating them.
Example:
terraform import aws_instance.web i-0123456789abcdef
Terraform records the resource relationship in:
terraform.tfstate
However, import only updates state; engineers must still write matching Terraform configuration files.
Why is terraform import needed?
terraform import is needed when organizations already have infrastructure created outside Terraform and want to start managing it with Infrastructure as Code.
Common scenarios:
- Existing production resources
- Cloud migrations
- Terraform adoption projects
- Legacy infrastructure management
Example:
Existing AWS resource:
EC2 Instance
|
v
terraform import
|
v
Terraform State
Import avoids manually recreating resources and reduces migration risk.
What resources can be imported into Terraform?
Most Terraform-managed resources that support import functionality can be imported. Availability depends on the provider and specific resource implementation.
Examples:
AWS:
terraform import aws_instance.server i-1234567890
Azure:
terraform import azurerm_resource_group.example /subscriptions/xxx/resourceGroups/example
Google Cloud:
terraform import google_compute_instance.vm projects/project/zones/us-east1-a/instances/example
Supported resources are documented by individual Terraform providers.
Does terraform import generate Terraform configuration files?
No, terraform import does not automatically generate Terraform configuration files. It only adds resource information into the Terraform state file.
Example:
terraform import aws_instance.web i-123456
Creates:
terraform.tfstate
But you still need:
resource "aws_instance" "web" {
}
Tools such as Terraform configuration generators can help create configuration from imported state, but the standard import command does not.
What is the difference between importing resources and creating new resources?
Importing connects existing infrastructure to Terraform state, while creating resources provisions new infrastructure through Terraform configuration.
Import:
terraform import aws_instance.web i-12345
Create:
terraform apply
Comparison:
| Operation | Infrastructure Change |
|---|---|
| Import | No resource creation |
| Apply | Creates resources |
Import is mainly used for Terraform adoption and migration scenarios.
What steps should be followed after importing a resource?
After importing a resource, engineers should create matching Terraform configuration and verify that Terraform does not attempt unexpected changes.
Typical workflow:
terraform import aws_instance.web i-12345
terraform plan
Steps:
- Write resource configuration
- Import resource
- Run
terraform plan - Adjust configuration
- Commit Terraform code
The goal is to achieve:
Terraform Configuration = Terraform State = Real Infrastructure
How do you import an AWS EC2 instance?
An AWS EC2 instance can be imported using its instance ID.
Example:
Terraform configuration:
resource "aws_instance" "web" {
}
Import:
terraform import aws_instance.web i-0abcd123456789
Verify:
terraform plan
Terraform compares the imported EC2 instance with the configuration and identifies missing attributes that need to be added.
How do you verify a successful Terraform import?
A successful import can be verified by checking Terraform state and running a Terraform plan.
View state:
terraform state list
Example:
aws_instance.web
Inspect resource:
terraform state show aws_instance.web
Then run:
terraform plan
A correctly configured import should show:
No changes. Your infrastructure matches the configuration.
What is Terraform state after an import?
After an import, Terraform state contains metadata about the existing resource, including its ID, attributes, and provider information.
Example:
terraform state show aws_instance.web
Displays:
id = i-0123456789
instance_type = t3.micro
The state allows Terraform to track and manage the imported resource during future operations.
How do you remove an imported resource from Terraform state without deleting it?
Terraform allows removing a resource from state without destroying the actual infrastructure using terraform state rm.
Example:
terraform state rm aws_instance.web
Result:
Resource removed from state
The cloud resource remains:
AWS EC2 Instance → Still Exists
Terraform State → No Longer Tracks It
This is useful when transferring resource ownership or removing Terraform management.
Scenario-Based Terraform Commands Interview Questions
Real-World Terraform Command Usage Scenarios
A teammate cloned the repository and receives provider errors. Which Terraform command should be executed first?
terraform init should be executed first because it initializes the Terraform working directory, downloads required provider plugins, configures backend settings, and installs required modules. A cloned repository does not contain downloaded provider binaries, so Terraform must prepare the environment before planning or applying infrastructure changes.
Example:
terraform init
Typical troubleshooting workflow:
git clone terraform-project
cd terraform-project
terraform init
terraform validate
terraform plan
The initialization process resolves provider dependencies defined in configuration files.
Your code formatting fails in a CI pipeline. Which command resolves it?
terraform fmt resolves Terraform formatting issues by automatically applying HashiCorp's standard formatting rules to configuration files. It ensures consistent indentation, spacing, and code structure across Terraform projects.
Example:
terraform fmt -recursive
CI validation:
terraform fmt -check -recursive
If formatting issues exist, developers can run:
terraform fmt
Formatting standards improve Terraform code readability, maintainability, and collaboration across DevOps teams.
Your manager wants to preview infrastructure changes without deploying them. Which command should you use?
terraform plan should be used because it generates an execution preview without modifying infrastructure. It compares the Terraform configuration with the current state and shows resources that will be created, updated, or deleted.
Example:
terraform plan
Sample output:
+ aws_instance.web will be created
~ aws_security_group.app will be updated
- aws_instance.old will be destroyed
Terraform planning is commonly required before production deployments to support infrastructure review and approval workflows.
You accidentally modified a cloud resource manually. Which Terraform command helps identify the drift?
terraform plan identifies infrastructure drift by comparing the current cloud environment against Terraform configuration and stored state. Manual changes made through cloud consoles or APIs are detected during the planning process.
Example:
terraform plan
Scenario:
Terraform configuration:
instance_type = "t3.micro"
Manual cloud change:
instance_type = "t3.large"
Terraform output:
~ instance_type = "t3.large" -> "t3.micro"
This helps teams restore infrastructure consistency.
How do you deploy only the reviewed infrastructure changes?
A saved Terraform plan should be generated and applied instead of running a fresh terraform apply. This ensures that the exact changes reviewed by engineers are deployed.
Workflow:
Create plan:
terraform plan -out=approved.tfplan
Review:
terraform show approved.tfplan
Deploy:
terraform apply approved.tfplan
This approach is commonly used in enterprise CI/CD pipelines where infrastructure changes require approval before production deployment.
You need to migrate existing infrastructure into Terraform management. Which command is used?
terraform import is used to bring existing infrastructure under Terraform management. It associates already-created resources with Terraform state without recreating them.
Example:
terraform import aws_instance.web i-0123456789abcdef
Migration workflow:
Existing Cloud Resource
|
v
terraform import
|
v
Terraform State
|
v
Terraform Configuration
After importing, engineers create matching Terraform configuration and validate the resource using:
terraform plan
A Terraform configuration contains syntax errors before deployment. Which command detects them?
terraform validate detects syntax errors, invalid Terraform expressions, missing arguments, and configuration structure problems before deployment.
Example:
terraform validate
Invalid configuration:
resource "aws_instance" {
ami = "abc"
}
Validation output:
Missing required argument
Terraform validation is commonly executed during pull requests to prevent incorrect Infrastructure as Code from reaching deployment environments.
Your deployment partially failed. How should you recover using Terraform commands?
After fixing the underlying issue, run terraform apply again. Terraform uses the state file to identify successfully completed resources and continue with remaining changes.
Example:
terraform apply
Recovery workflow:
terraform apply
|
v
Partial Failure
|
v
Fix Problem
|
v
terraform apply
Terraform does not automatically roll back completed resources. The state file allows Terraform to resume from the current infrastructure condition.
How do you safely remove all resources created by Terraform?
Use terraform plan -destroy first to review deletion actions, then execute terraform destroy after approval.
Preview:
terraform plan -destroy
Execute:
terraform destroy
Recommended production process:
Review Destroy Plan
|
v
Approval
|
v
terraform destroy
This prevents accidental deletion of critical infrastructure components.
When would you use terraform plan -destroy instead of terraform destroy?
terraform plan -destroy is used when you want to review what Terraform will delete without actually removing resources. It is preferred during audits, cleanup preparation, and production change reviews.
Example:
terraform plan -destroy
Actual deletion:
terraform destroy
The planning command improves operational safety because engineers can identify unexpected resource removals before execution.
CI/CD and Best Practices Terraform Commands Interview Questions
DevOps and Enterprise Terraform Practices
Which Terraform commands are typically executed in a CI pipeline?
CI pipelines commonly execute Terraform commands that validate code quality, generate plans, and verify infrastructure changes before deployment.
Typical workflow:
terraform fmt -check
terraform init
terraform validate
terraform plan
Production deployment stages may include:
terraform apply
Common CI/CD tools:
- GitHub Actions
- Jenkins
- GitLab CI/CD
- Azure DevOps Pipelines
Terraform automation improves consistency and reduces manual infrastructure changes.
What is the recommended Terraform command execution order in a deployment pipeline?
The recommended Terraform workflow follows a sequence that validates, previews, and applies infrastructure changes.
Standard workflow:
terraform init
terraform fmt -check
terraform validate
terraform plan -out=tfplan
terraform apply tfplan
Each command has a specific purpose:
| Command | Purpose |
|---|---|
| init | Install dependencies |
| fmt | Format code |
| validate | Check configuration |
| plan | Preview changes |
| apply | Deploy infrastructure |
This sequence is widely adopted for enterprise Infrastructure as Code practices.
Why should terraform plan be reviewed before terraform apply?
Reviewing terraform plan before terraform apply helps teams identify unexpected infrastructure changes before they affect cloud environments. It provides visibility into resource creation, updates, replacements, and deletions.
Example:
terraform plan -out=production.tfplan
Review:
terraform show production.tfplan
Benefits:
- Prevent accidental deletion
- Detect security changes
- Support approval workflows
- Improve deployment confidence
Production Terraform workflows usually separate planning and applying stages.
Why should terraform fmt -check be included in pull requests?
terraform fmt -check ensures Terraform code follows standardized formatting rules before merging changes. It prevents inconsistent styles across infrastructure repositories.
Example:
terraform fmt -check -recursive
Benefits:
- Cleaner code reviews
- Consistent Terraform modules
- Reduced formatting-related changes
- Improved maintainability
Many DevOps teams enforce formatting checks as an automated quality gate.
Why is terraform validate important before infrastructure deployment?
terraform validate detects configuration problems before Terraform interacts with cloud providers. It helps identify errors early and prevents invalid Infrastructure as Code from reaching deployment stages.
Example:
terraform validate
Validation catches:
- Syntax errors
- Invalid references
- Incorrect resource definitions
- Configuration issues
It is often combined with:
terraform fmt
terraform validate
terraform plan
to create a reliable Terraform quality pipeline.
How do remote state backends affect Terraform command execution?
Remote state backends allow Terraform state files to be stored centrally and shared securely between team members. Commands such as plan, apply, and destroy interact with the remote state instead of a local file.
Example backend:
terraform {
backend "s3" {
bucket = "terraform-state"
key = "prod/state.tfstate"
region = "us-east-1"
}
}
Benefits:
- Team collaboration
- State locking
- Backup support
- Centralized management
Remote state is essential for enterprise Terraform deployments.
How can Terraform commands be automated in GitHub Actions?
Terraform commands can be automated in GitHub Actions by defining workflow steps that initialize, validate, plan, and apply infrastructure.
Example:
steps:
- name: Terraform Init
run: terraform init
- name: Terraform Validate
run: terraform validate
- name: Terraform Plan
run: terraform plan
Automation provides:
- Consistent deployments
- Automated reviews
- Infrastructure testing
- Reduced manual operations
Production environments often require approval before the apply stage.
What are the risks of using terraform apply -auto-approve?
terraform apply -auto-approve removes the manual confirmation step and immediately executes infrastructure changes. While useful for automation, it can increase the risk of accidental modifications.
Example:
terraform apply -auto-approve
Potential risks:
- Unreviewed changes
- Accidental resource deletion
- Incorrect environment deployment
Best practice:
terraform plan -out=tfplan
terraform apply tfplan
Use automatic approval only with strong CI/CD controls and testing.
Which Terraform commands require cloud provider credentials?
Commands that interact with cloud infrastructure typically require provider authentication. Commands like plan, apply, destroy, and some import operations communicate with provider APIs.
Examples:
AWS credentials:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
Commands requiring access:
terraform plan
terraform apply
terraform destroy
terraform import
Commands such as:
terraform fmt
terraform validate
usually do not require cloud credentials because they operate locally.
What are Terraform command best practices for production environments?
Production Terraform usage requires controlled workflows, state management, security practices, and automated validation.
Recommended workflow:
terraform fmt -check
terraform init
terraform validate
terraform plan -out=prod.tfplan
terraform apply prod.tfplan
Best practices:
- Use remote state backends
- Enable state locking
- Review plans before applying
- Use least-privilege cloud permissions
- Separate environments
- Protect critical resources
These practices improve reliability, security, and governance for enterprise Infrastructure as Code operations.
