Terraform Basics

Q1: What is Terraform and why is it used?

Ans: Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows you to define, provision, and manage infrastructure across multiple cloud providers using declarative configuration files. It is used for automation, consistency, and reproducibility of infrastructure deployments.

Q2: Explain the difference between Terraform and other configuration management tools like Ansible or Chef.

Ans: Terraform focuses on infrastructure provisioning (servers, networks, storage), while Ansible and Chef are primarily configuration management tools (installing packages, managing services). Terraform is declarative, ensuring desired state, whereas Ansible is procedural, executing tasks step by step.

Q3: What are Terraform providers?

Ans: Providers are plugins that allow Terraform to interact with APIs of cloud platforms and services (e.g., AWS, Azure, GCP). Each provider defines resources and data sources that Terraform can manage. Example: AWS provider manages EC2, S3, IAM resources.

Q4: What is the difference between Terraform modules and resources?

Ans: Resources are the basic building blocks (e.g., aws_instance, aws_s3_bucket). Modules are collections of resources grouped together for reuse and abstraction. Modules help organize code, enforce best practices, and simplify complex deployments.

Q5: Explain Terraform state and why it is important.

Ans: Terraform state is a file that maps real-world infrastructure to your configuration. It tracks resource metadata, dependencies, and IDs. State is critical for planning changes, detecting drift, and enabling collaboration. It can be stored locally or remotely (e.g., S3, Terraform Cloud).

Q6: What is the difference between local and remote state?

Ans: Local state stores the state file on your machine. Remote state stores it in a shared backend (like S3, GCS, or Terraform Cloud) enabling collaboration, locking, and consistency across teams.

Q7: How does Terraform handle dependencies between resources?

Ans: Terraform automatically infers dependencies based on resource references. For example, if an EC2 instance references a subnet ID, Terraform ensures the subnet is created first. Explicit dependencies can be defined using the `depends_on` attribute.

Q8: What is a Terraform backend?

Ans: A backend defines where Terraform state is stored and how operations are executed. Examples include local, S3, GCS, and Terraform Cloud. Backends enable remote collaboration, state locking, and secure storage.

Q9: Explain the difference between `terraform plan` and `terraform apply`.

Ans: `terraform plan` shows the execution plan, detailing what changes will be made without applying them. `terraform apply` executes the plan, creating or modifying resources as defined in the configuration.

Q10: What is the use of `terraform init`?

Ans: `terraform init` initializes a working directory. It downloads provider plugins, sets up the backend, and prepares the environment for further commands like plan and apply.

Q11: How do you manage sensitive data in Terraform?

Ans: Sensitive data can be managed using variables marked as `sensitive`, environment variables, or secret management tools (Vault, AWS Secrets Manager). Remote backends and encryption should be used to secure state files.

Q12: What are Terraform workspaces?

Ans: Workspaces allow multiple state files for the same configuration, enabling environment separation (e.g., dev, staging, prod). Each workspace maintains its own state, making it easier to manage multiple environments.

Q13: Explain the difference between `count` and `for_each` in Terraform.

Ans: `count` creates multiple instances of a resource based on a numeric value. `for_each` creates resources based on a map or set, allowing more granular control and unique identifiers for each resource.

Q14: What is Terraform Cloud and how is it different from open-source Terraform?

Ans: Terraform Cloud is a SaaS offering by HashiCorp that provides remote state management, collaboration, policy enforcement, and CI/CD integration. Open-source Terraform requires manual setup of backends and collaboration tools.

Q15: How do you perform Terraform upgrades?

Ans: Upgrades involve updating provider versions in `versions.tf`, running `terraform init -upgrade`, and reviewing breaking changes in release notes. State migration may be required if provider schemas change.

Q16: What is the difference between `terraform import` and `terraform taint`?

Ans: `terraform import` brings existing infrastructure into Terraform state. `terraform taint` marks a resource for recreation during the next apply, useful for fixing corrupted or misconfigured resources.

Q17: Explain the concept of immutable infrastructure in Terraform.

Ans: Immutable infrastructure means replacing resources instead of modifying them in place. Terraform supports this by destroying and recreating resources when changes require it, ensuring consistency and avoiding drift.

Q18: How do you handle drift in Terraform?

Ans: Drift occurs when infrastructure changes outside Terraform. Running `terraform plan` detects drift. Solutions include re-applying configurations, importing changes, or reconciling differences manually.

Q19: What are some best practices for writing Terraform code?

Ans: 1. Use modules for reusability. 2. Store state remotely with locking. 3. Use version constraints for providers. 4. Separate environments with workspaces. 5. Keep variables and outputs organized. 6. Document code and enforce policies with Sentinel or OPA.

Q20: Suppose you lose your Terraform state file and do not have any backup copy, what will happen?

Ans: The impact is as follow: 1. Loss of Resource Tracking – Terraform will no longer know which resources exist in your infrastructure, breaking the link between configuration and reality.
2. Risk of Duplication – running 'terraform apply' may attempt to recreate resources that already exist, leading to conflicts or duplicate infrastructure.
3. Inability to Update/Destroy – without state, Terraform cannot safely update or destroy resources because it lacks resource IDs and metadata.
4. Manual Recovery – engineers must manually re-import resources into a new state file using 'terraform import', which is tedious and error-prone.
5. Production Impact – potential downtime, unexpected costs from duplicate resources, and operational delays.
6. Best Practice – always store state in a remote backend (S3, GCS, Azure Blob) with versioning and backups enabled, and use state locking to prevent corruption.

Q21: What happens if two engineers run 'terraform apply' at the same time on the same state file?

Ans: The impact is as follow: 1. State Corruption – simultaneous writes can corrupt the state file.
2. Conflicting Changes – resources may be updated inconsistently, leading to drift.
3. Best Practice – use remote backends with state locking (e.g., S3 + DynamoDB, GCS + Cloud Lock) to prevent concurrent modifications.

Q22: If your Terraform plan shows resources being destroyed and recreated unexpectedly, how would you handle it?

Ans: The approach is as follow: 1. Investigate Drift – check if manual changes were made outside Terraform.
2. Check Configuration – review changes in resource arguments that force recreation.
3. Mitigation – use 'terraform import' to bring external changes into state or adjust configuration to avoid destructive updates.

Q23: How would you manage sensitive data like passwords or API keys in Terraform?

Ans: The solution is as follow: 1. Avoid Hardcoding – never store secrets directly in .tf files.
2. Use Variables – pass sensitive values via environment variables or tfvars files.
3. Vault Integration – integrate with secret managers like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault.
4. Mark Sensitive – use 'sensitive = true' in variable definitions to prevent accidental logging.

Q24: What would you do if Terraform shows a resource in 'tainted' state?

Ans: The handling is as follow: 1. Meaning – a tainted resource will be destroyed and recreated on next apply.
2. Cause – usually due to failed provisioning or manual tainting.
3. Action – run 'terraform apply' to recreate, or use 'terraform untaint' if recreation is not desired.

Q25: How do you handle a situation where Terraform needs to manage resources created manually before Terraform adoption?

Ans: The approach is as follow: 1. Import Resources – use 'terraform import' to bring existing resources into state.
2. Update Configuration – write matching .tf definitions for those resources.
3. Validate – run 'terraform plan' to ensure no unintended changes.
4. Best Practice – avoid manual resource creation going forward to prevent drift.

Q26: What is Terraform drift and why does it matter?

Ans: Terraform drift occurs when the actual cloud infrastructure no longer matches the Terraform state due to manual or external changes. It matters because Terraform may attempt to 'correct' these differences during the next plan/apply, potentially undoing intentional fixes or introducing instability.

Q27: How can you detect Terraform drift?

Ans: Run `terraform plan` to compare desired state with actual cloud resources. The plan output highlights differences. Regular drift detection can also be automated in CI/CD pipelines to catch discrepancies early.

Q28: What are common causes of Terraform drift?

Ans: Manual console changes, hotfixes applied outside IaC, cloud provider defaults changing, or scripts/tools modifying resources directly. Even small changes like tags or security group rules can trigger drift.

Q29: How do you safely resolve Terraform drift?

Ans: First, identify which changes were intentional vs accidental. For intentional changes, update Terraform code to reflect reality. For accidental changes, let Terraform revert them via apply. Use `terraform refresh` or state reconciliation to sync state, and re-run plan until no drift remains.

Q30: What practices help prevent Terraform drift?

Ans: Restrict console access, enforce IaC-only changes for production, add drift checks in CI before apply, and document emergency change workflows. These measures ensure infrastructure changes remain consistent and traceable.

Q31: Why is blindly applying Terraform after drift risky?

Ans: Because Terraform may overwrite intentional manual fixes or emergency changes. Without reviewing the plan output, you risk breaking production by reverting critical settings that were applied outside Terraform.