Terraform Scenario Based

Q1: What is Terraform and how does it manage infrastructure state?

Ans: Terraform is an Infrastructure as Code (IaC) tool that provisions and manages cloud and on-prem resources declaratively. It maintains a state file (`terraform.tfstate`) that records the current infrastructure and maps it to the configuration. This state enables Terraform to detect changes, plan updates, and avoid recreating resources unnecessarily. State can be stored locally or remotely (S3, GCS, Azure Blob) for collaboration.

Q2: Terraform state file is accidentally deleted β€” how would you recover the infrastructure state?

Ans: If the state file is deleted, Terraform loses track of managed resources. Recovery involves: 1) Restoring from a backup if remote backend snapshots exist. 2) Running `terraform import` to re-map existing resources into a new state file. 3) Using cloud provider consoles to identify resource IDs and import them. Best practice is to always use remote backends with versioning enabled to prevent permanent loss.

Q3: Terraform state file is locked β€” how do you resolve state lock issues?

Ans: State locks prevent concurrent modifications. If a lock persists (e.g., due to a crashed process), check the backend (DynamoDB for S3, Consul, etc.) and manually remove the lock entry. Use `terraform force-unlock ` cautiously to release locks. Always confirm no other team member is running Terraform to avoid state corruption.

Q4: Multiple team members are working on the same Terraform code and state β€” how do you prevent conflicts?

Ans: Conflicts occur when multiple people run Terraform simultaneously. Prevent this by: 1) Using remote backends with state locking (S3 + DynamoDB, GCS + Cloud Storage Lock). 2) Enforcing CI/CD pipelines for Terraform runs instead of local execution. 3) Structuring code into modules and workspaces to isolate environments. This ensures safe collaboration and avoids race conditions.

Q5: Terraform apply failed in the middle of execution β€” how do you recover from a partial deployment?

Ans: Partial deployments leave infrastructure inconsistent. Run `terraform plan` again to see pending changes. Terraform will reconcile differences and continue. If resources are stuck, manually clean them up in the cloud provider and re-run `terraform apply`. Best practice is to use `-auto-approve=false` and review plans carefully to minimize risk.

Q6: Terraform shows drift between infrastructure and state β€” how do you identify and fix it?

Ans: Drift occurs when resources are modified outside Terraform. Detect drift with `terraform plan` or `terraform refresh`. Fix by either updating the configuration to match reality or re-importing resources. In production, enforce policies to prevent manual changes and use drift detection tools integrated with CI/CD pipelines.

Q7: Terraform plan shows unexpected resource changes β€” how do you troubleshoot it?

Ans: Unexpected changes may result from variable misconfiguration, provider version differences, or default values. Troubleshoot by: 1) Checking variable precedence (CLI `-var`, environment, tfvars). 2) Reviewing provider changelogs. 3) Inspecting module outputs. Use `terraform plan -out=planfile` and `terraform show planfile` for detailed diffs.

Q8: Remote backend (like S3) is not accessible β€” how do you debug backend issues?

Ans: Backend errors often stem from IAM permission issues, network connectivity, or misconfigured bucket names. Debug by testing access with AWS CLI (`aws s3 ls`), checking IAM policies, and verifying backend configuration in `terraform { backend "s3" { ... } }`. Ensure encryption and versioning are enabled for resilience.

Q9: Terraform resources are getting recreated unexpectedly β€” what could be the cause?

Ans: Recreation occurs when immutable fields change (e.g., instance type, subnet). It can also result from provider bugs or drift. Troubleshoot by checking `terraform plan` output for `forces new resource`. Fix by adjusting configuration to avoid unnecessary changes or using lifecycle rules (`lifecycle { prevent_destroy = true }`).

Q10: Sensitive values are visible in Terraform state β€” how do you secure them?

Ans: Terraform state may contain secrets (passwords, tokens). Secure by: 1) Using remote backends with encryption (S3 + KMS). 2) Enabling `sensitive = true` in outputs to hide values. 3) Integrating with secret managers (Vault, AWS Secrets Manager). Avoid committing state files to version control.

Q11: Terraform modules are not working as expected β€” how do you debug module issues?

Ans: Debug by checking module source paths, versions, and input variables. Run `terraform get -update` to refresh modules. Inspect outputs with `terraform console`. If using private registries, verify authentication. In production, pin module versions to avoid breaking changes.

Q12: A resource dependency is not respected β€” how do you handle dependency issues?

Ans: Terraform infers dependencies via references. If not respected, explicitly define with `depends_on`. For example, ensure a database is created before an application server. Debug with `terraform graph` to visualize dependencies. Best practice is to avoid hardcoding and rely on outputs/variables for implicit dependencies.

Q13: Terraform variables are not being picked correctly β€” how do you debug variable precedence?

Ans: Variable precedence is: CLI `-var` > environment variables > `terraform.tfvars` > default values. Debug by running `terraform plan -var-file=...` and checking logs. Ensure variable names match exactly. In CI/CD, confirm environment variables are passed correctly.

Q14: Terraform apply takes too long β€” how do you optimize performance?

Ans: Long applies may result from sequential resource creation or API throttling. Optimize by: 1) Using `-parallelism=N` to increase concurrency. 2) Splitting infrastructure into smaller modules. 3) Using provider-specific optimizations (batch APIs). Monitor cloud provider rate limits to avoid throttling.

Q15: Infrastructure created by Terraform is not accessible after deployment β€” how do you troubleshoot?

Ans: Check networking (VPC, subnets, security groups, firewalls). Verify DNS records and load balancer health checks. Use `terraform output` to confirm endpoints. Debug with cloud provider CLI tools. Often, IAM or networking misconfigurations block access.

Q16: Terraform workspace is not switching properly β€” how do you fix workspace-related issues?

Ans: Workspaces isolate state. If switching fails, run `terraform workspace list` and `terraform workspace select `. Ensure backend supports workspaces. Debug by checking `.terraform/environment` file. Best practice is to use separate backends per environment instead of workspaces for production isolation.

Q17: Terraform provider version conflict occurs β€” how do you resolve provider dependency issues?

Ans: Conflicts arise when modules require different provider versions. Fix by pinning provider versions in `required_providers`. Use `terraform init -upgrade` to reconcile. In production, maintain a provider version matrix and test upgrades in staging.

Q18: Terraform apply fails due to API rate limits β€” how do you handle throttling issues?

Ans: Cloud providers enforce rate limits. Terraform may hit these during large deployments. Fix by reducing parallelism (`-parallelism=5`), batching resources, or using retries (`provider { request_timeout }`). Monitor API quotas and request increases if needed.

Q19: Terraform cannot authenticate to cloud provider β€” how do you debug authentication failures?

Ans: Check credentials in environment variables, shared config files, or Jenkins secrets. Run provider CLI (`aws sts get-caller-identity`) to confirm. Ensure IAM roles or service accounts are correctly configured. In CI/CD, verify secret injection and role assumptions.

Q20: Terraform plan works locally but fails in CI/CD pipeline β€” how do you troubleshoot?

Ans: Differences in environment variables, backend access, or provider credentials often cause failures. Debug by comparing local and pipeline configs. Ensure CI/CD runners have access to remote backends and credentials. Use `terraform plan -out` locally and apply in CI/CD to reduce drift.

Q21: Resources are manually modified outside Terraform β€” how do you detect and fix configuration drift?

Ans: Configuration drift occurs when infrastructure is changed directly in the cloud provider console or via other tools. Detect drift by running `terraform plan` or `terraform refresh` to compare actual resources with the state file. Fix by either updating Terraform code to reflect the manual changes or re-importing resources using `terraform import`. Best practice is to enforce policies that prevent manual changes and integrate drift detection into CI/CD pipelines.

Q22: Terraform destroy fails due to dependencies β€” how do you resolve it safely?

Ans: Destroy failures often occur when resources depend on each other (e.g., VPCs with subnets, IAM roles with attached policies). Troubleshoot by checking error messages and dependency graphs (`terraform graph`). Resolve by manually removing dependent resources first, or using `depends_on` to enforce correct deletion order. In production, use `terraform destroy -target=resource` cautiously to remove specific resources without breaking dependencies.

Q23: Remote state corruption occurs β€” how do you recover state safely?

Ans: Remote state corruption can happen due to backend issues or concurrent writes. Recovery involves restoring from backend versioning (S3 with versioning, GCS object history). If no backup exists, re-import resources with `terraform import`. Always enable state locking (DynamoDB, Consul) and versioning to prevent corruption. In production, monitor backend health and enforce CI/CD pipelines for controlled state updates.

Q24: Multiple environments (dev, stage, prod) need isolation β€” how do you design Terraform structure?

Ans: Isolate environments by using separate state files and backends for each environment. Structure code with modules for reusable components and environment-specific workspaces or directories (`environments/dev`, `environments/prod`). Use remote backends with unique keys per environment. In production, enforce environment isolation with separate IAM roles, credentials, and pipelines to prevent accidental cross-environment changes.

Q25: Terraform outputs are not available after deployment β€” how do you debug?

Ans: If outputs are missing, check the `output` blocks in configuration. Ensure outputs are not marked `sensitive` if you expect them in CLI. Run `terraform output` to list values. If outputs depend on resources that failed, fix those resources first. In CI/CD, confirm that the pipeline captures outputs correctly. Best practice is to use outputs for passing values between modules and environments.

Q26: Infrastructure deployment fails due to incorrect IAM permissions β€” how do you troubleshoot?

Ans: IAM permission issues manifest as API errors during `terraform apply`. Debug by checking error messages and running provider CLI commands (`aws sts get-caller-identity`). Verify that the IAM role or service account has required permissions. Fix by updating IAM policies or assigning correct roles. In production, follow least privilege principles and pre-validate IAM permissions before deployment.

Q27: Terraform cannot find required modules β€” how do you fix module source issues?

Ans: Module errors occur when sources are misconfigured. Check the `source` path in module blocks. Run `terraform get -update` to refresh modules. If using private registries, verify authentication. For Git-based modules, ensure branch/tag references are correct. In production, pin module versions and use a private module registry for reliability.

Q28: Changes are applied to wrong environment β€” how do you prevent such mistakes?

Ans: Accidental changes occur when the wrong workspace or backend is used. Prevent this by enforcing environment-specific backends and credentials. Use CI/CD pipelines with explicit environment variables. Add safeguards like `terraform workspace select` in scripts. In production, implement approval workflows and naming conventions to avoid cross-environment mistakes.

Q29: Terraform rollback is required after a failed deployment β€” how do you handle rollback strategy?

Ans: Terraform does not have native rollback. To recover, re-apply the previous known configuration or state. Use version control to revert code changes and re-run `terraform apply`. If resources were partially created, manually clean them up before re-applying. In production, maintain tagged releases of Terraform code and state snapshots to enable controlled rollbacks.

Q30: How do you troubleshoot a complete infrastructure deployment failure using Terraform?

Ans: For full deployment failures, start by reviewing `terraform plan` and error logs. Identify failing resources and check provider API limits, IAM permissions, and network connectivity. Use `terraform apply -target=resource` to deploy critical components incrementally. Debug dependencies with `terraform graph`. In production, break infrastructure into smaller modules, run staged deployments, and monitor provider quotas to reduce risk.