1. What is Terraform?
Terraform is an open-source Infrastructure as Code (IaC) tool by HashiCorp that lets you define, provision, and manage infrastructure using configuration files.
2. Key Benefits of Terraform
-
Platform-agnostic (AWS, Azure, GCP, etc.)
-
Declarative language (HCL)
-
Infrastructure automation
-
State management and dependency graph
-
Modular and reusable code
3. Terraform Components
Providers & Backend
Resources
Variables
Map Variables & Data Sources Example
Outputs
4. Terraform Project Structure
Flat structure
Modular structure
Environment-specific (dev/prod)
5. Terraform Modules: Create & Use
What is a Module?
-
A container for multiple resources grouped together.
-
Promotes code reuse and maintainability.
Example: Creating a Simple VPC Module
Folder: modules/vpc/
main.tf
variables.tf
outputs.tf
Using the Module in Root Configuration
main.tf
Benefits of Modules
-
Reusability across projects/environments
-
Cleaner codebase
-
Easier maintenance and upgrades
6. Locals and Variable Precedence
Variable precedence order (high to low):
-
CLI flags (
-var
) -
Environment variables
-
terraform.tfvars
-
*.auto.tfvars
-
Default values in variable blocks
7. Terraform Commands Cheat Sheet
Command | Purpose |
---|---|
terraform init | Initialize the project |
terraform plan | Preview changes |
terraform apply | Apply infrastructure changes |
terraform destroy | Delete all resources |
terraform validate | Validate configuration |
terraform fmt | Format configuration files |
8. Terraform Variable Types
Type | Description | Example |
---|---|---|
string | Text value | type = string |
number | Numeric value | type = number |
bool | Boolean true/false | type = bool |
list | Ordered list | type = list(string) |
map | Key-value pairs | type = map(string) |
object | Complex structured data | type = object({name=string, age=number}) |
any | Any type | type = any |
9. Terraform Interview Questions & Answers (50)
Basics
1. What is Terraform?
Terraform is an open-source Infrastructure as Code tool for defining and provisioning cloud and on-prem infrastructure using configuration files.
2. What are Terraform providers?
Providers are plugins that allow Terraform to interact with APIs of cloud providers or services (AWS, Azure, GCP, etc.).
3. What is the purpose of the Terraform backend?
It defines where and how Terraform stores its state file and enables state locking.
4. What is Terraform state?
A snapshot of the infrastructure Terraform manages, used to map resources in config to real-world objects.
5. How do you handle multiple environments in Terraform?
By using workspaces, separate directories, or different variable files per environment.
Intermediate
6. What are modules in Terraform?
Modules are containers for multiple resources that promote reusability and better organization.
7. How do you pass variables to Terraform?
Through terraform.tfvars
, CLI flags, environment variables, or default values.
8. What is the difference between count
and for_each
?
count
creates multiple instances indexed by number, for_each
creates resources from keys in a map or set.
9. How do you manage secrets in Terraform?
Use environment variables, encrypted backends, or secret managers. Avoid hardcoding secrets.
10. What are provisioners?
Provisioners execute scripts or commands on a resource after creation or before destruction.
Advanced
11. What is a Terraform workspace?
An isolated state environment to manage multiple distinct states within the same configuration.
12. How do you import existing infrastructure into Terraform?
With terraform import
command to bring existing resources under Terraform management.
13. What are data sources in Terraform?
They allow Terraform to query existing infrastructure or external data for use in configuration.
14. What is a lifecycle meta-argument?
Controls create/update/delete behavior of resources (e.g., prevent destroy).
15. How do you enforce resource dependencies?
Implicit via resource references, or explicit using depends_on
.
Expert
16. How do you handle provider versioning?
Specify required_providers
block with version constraints in Terraform configuration.
17. What is remote state locking?
Prevents multiple concurrent Terraform executions from corrupting the state.
18. How do you test Terraform configurations?
Using terraform validate
, terraform fmt
, and external tools like Terratest.
19. What are dynamic blocks?
Blocks that generate nested repeated blocks dynamically based on variables.
20. How can you structure Terraform code for large projects?
Use modules, environment folders, remote backends, and versioned modules.
More Questions
21. What is the difference between declarative and imperative IaC?
Terraform is declarative — you describe what you want, not how to do it.
22. How can Terraform automate infrastructure rollbacks?
By applying previous versions of state or configurations.
23. What happens when you run terraform apply
without changes?
Terraform detects no changes and does nothing.
24. How to handle cross-account AWS resources?
Use multiple provider aliases with different credentials.
25. How do you secure Terraform state?
Use encrypted remote backends with strict access controls.
Additional Questions
26. What is the purpose of terraform fmt
?
To format Terraform configuration files according to canonical style.
27. How can you split Terraform configurations for team collaboration?
By using modules and separating state files via workspaces or backend configs.
28. What is the difference between terraform plan
and terraform apply
?
plan
shows proposed changes, apply
executes them.
29. Can Terraform be used with on-prem resources?
Yes, providers exist for many on-prem technologies.
30. How do you use output values?
To expose resource attributes after apply for other configs or scripts.
More Advanced Questions
31. What are meta-arguments in Terraform?
Special arguments like count
, depends_on
, lifecycle
, which modify resource behavior.
32. How does Terraform handle drift detection?
By comparing real infrastructure with state during plan
.
33. How do you upgrade Terraform versions safely?
Test with terraform validate
and in isolated environments before production.
34. How do you manage secrets with Terraform Cloud?
Use Terraform Cloud’s variable sets with sensitive flag.
35. What is the purpose of terraform taint
?
Marks a resource for forced recreation on next apply.
Final Questions
36. How do locals differ from variables?
Locals are constants within a module, variables are inputs.
37. Can Terraform manage Kubernetes resources?
Yes, using Kubernetes provider.
38. What is a provider alias?
Allows multiple configurations of the same provider.
39. How do you debug Terraform?
Use TF_LOG=DEBUG
environment variable.
40. What are dynamic blocks useful for?
Generating repetitive nested blocks conditionally or from lists/maps.
41. How can you reduce code duplication in Terraform?
Use modules and for_each
with maps or lists.
42. How does Terraform handle dependencies between resources?
Automatically detects from resource references; explicit dependencies via depends_on
.
43. What is the difference between local-exec
and remote-exec
provisioners?
local-exec
runs locally; remote-exec
runs commands on the provisioned resource.
44. How do you lock Terraform state?
Using backends like S3 with DynamoDB or Terraform Cloud.
45. Can Terraform be integrated into CI/CD pipelines?
Yes, commonly integrated for automated infrastructure deployment.
46. What is the use of terraform state
commands?
To inspect or modify the Terraform state file.
47. How can you output multiple values from a module?
Define multiple outputs in the module.
48. What is the significance of terraform validate
?
Checks syntax and internal consistency without contacting providers.
49. How do you handle version control for Terraform state?
Keep state remote and avoid manual edits; use locking and encryption.
50. Can Terraform manage secrets directly?
No, best practice is to use external secret managers or environment variables.
How Provisioners Work
-
They run on the target resource after resource creation (
create
provisioner) or before resource destruction (destroy
provisioner). -
Most common provisioners are
local-exec
(runs commands locally where Terraform is running) andremote-exec
(runs commands on the remote resource via SSH or WinRM).
Types of Provisioners
Provisioner | Description | Example Use Case |
---|---|---|
local-exec | Runs commands locally on your machine | Generate config files, trigger local scripts |
remote-exec | Runs commands on remote machine over SSH/WinRM | Install software, configure services |
file | Copies files from local machine to remote resource | Upload config files or scripts |
Example of remote-exec
Provisioner with AWS EC2
Explanation:
-
After EC2 is created, the
remote-exec
provisioner connects via SSH. -
Runs commands to update OS, install Apache HTTP server, start and enable it.
-
Uses SSH private key and public IP of the instance to connect.
Example of local-exec
Provisioner
Explanation:
-
After EC2 instance is created, runs a local command.
-
Appends the new instance’s public IP to a local file called
ip_list.txt
.
How does terraform import
work?
-
It links an existing real-world resource to a resource block in your Terraform configuration.
-
The resource must already exist.
-
You need to write the resource block in your
.tf
files matching the resource type. -
Then run
terraform import
specifying the resource and its real ID.
How to import
Basic Syntax
-
ADDRESS
: The Terraform resource address (e.g.,aws_instance.my_ec2
). -
ID
: The provider-specific identifier of the resource (e.g., instance ID for AWS:i-0abcd1234efgh5678
).
Example: Importing an existing AWS EC2 instance
-
Write resource block in Terraform config:
-
Run import command:
-
Terraform imports the state and links it with the resource block.
-
Run
terraform plan
to see the current state and update the config to match actual resource properties (add missing arguments).
Important Notes
-
Import does not create or modify resources. It only updates Terraform’s state.
-
After import, the resource configuration must be updated to reflect the real resource’s attributes. Otherwise, Terraform might want to modify or destroy resources on next
apply
. -
You can import multiple resources by running multiple import commands.
-
Not all resources support import (check Terraform provider docs).
-
Import only affects Terraform state; it does not generate
.tf
files for you.
Use Case Example: Importing an existing S3 bucket
Terraform config:
Import command:
🗂 Terraform State File Overview
No comments:
Post a Comment