This guide provides a curated list of common Terraform interview questions to help you prepare for your next DevOps or Cloud Engineer role. Master these concepts to demonstrate your expertise in Infrastructure as Code and automated infrastructure management.
Last Updated: Aug 25, 2025
Table of Contents
Core Concepts & IaC
1. What is Terraform?
Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp. It enables users to define and provision data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language (HCL), or optionally JSON. You can learn more from the official Terraform website.
2. What is Infrastructure as Code (IaC)?
Infrastructure as Code (IaC) is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools. It allows you to treat your infrastructure like application code, enabling version control, automated testing, and continuous deployment.
3. What are the main advantages of using Terraform?
- Platform Agnostic: Supports multiple cloud providers (AWS, Azure, GCP) and on-premise solutions.
- Declarative Language: You describe the desired end state, and Terraform figures out how to get there.
- State Management: Keeps track of your infrastructure, allowing for easy updates and destruction.
- Modularity: Reusable modules allow for better organization and consistency.
- Execution Plans: The `plan` command lets you preview changes before applying them.
4. What is the difference between Terraform and other IaC tools like Ansible or CloudFormation?
- Terraform vs. Ansible: Terraform is declarative (describes the end state), while Ansible is primarily procedural (describes the steps to get there). Terraform excels at provisioning, while Ansible excels at configuration management.
- Terraform vs. CloudFormation: Terraform is cloud-agnostic, supporting many providers. CloudFormation is specific to Amazon Web Services (AWS).
5. What are the key components of Terraform?
- Configuration Files: Files with .tf extension containing infrastructure definitions
- Providers: Plugins that interact with APIs of cloud providers and services
- Resources: Infrastructure objects that Terraform manages
- State: The stored representation of infrastructure managed by Terraform
- Modules: Reusable containers for multiple resources
- Variables: Parameters that allow customization of Terraform configurations
- Outputs: Values that are returned after applying the configuration
6. What is the difference between declarative and imperative approaches in IaC?
In a declarative approach (used by Terraform), you specify what the desired end state should be, and the tool determines how to achieve that state. In an imperative approach (used by tools like Ansible), you specify the exact steps needed to configure the infrastructure.
7. What is HCL and why is it used in Terraform?
HCL (HashiCorp Configuration Language) is a configuration language created by HashiCorp. It is designed to be both human-readable and machine-friendly. HCL is used in Terraform because it provides a clear syntax for defining infrastructure, supports JSON compatibility, and allows for expressions and functions to create dynamic configurations.
8. What is a Terraform provider?
A Terraform provider is a plugin that implements resource types for a specific infrastructure platform (like AWS, Azure, GCP) or service (like Kubernetes, DNS). Providers are responsible for understanding API interactions and exposing resources that can be managed through Terraform.
9. What is a Terraform resource?
A Terraform resource is the most important element in the Terraform language. Each resource block describes one or more infrastructure objects, such as virtual networks, compute instances, or higher-level components like DNS records. Resources have a type and name, and contain arguments to configure the resource.
10. What is the purpose of the Terraform workflow?
The Terraform workflow typically follows these steps: Write → Plan → Apply. First, you write the infrastructure code. Then, you run terraform plan
to see what changes will be made. Finally, you run terraform apply
to implement those changes. This workflow ensures predictability and reduces the risk of unintended changes to infrastructure.
Configuration & Syntax (HCL)
11. What are the basic HCL syntax elements in Terraform?
Basic HCL syntax elements include:
- Blocks: Containers for other content, represented as
block_type "label" { ... }
- Arguments: Assign a value to a name, using the syntax
name = value
- Expressions: References to values, either literal or referenced
- Comments: Single-line (
//
or#
) and multi-line (/* */
)
12. How do you define a variable in Terraform?
Variables are defined in a variable
block:
variable "instance_type" {
description = "The type of EC2 instance to launch"
type = string
default = "t2.micro"
}
13. How do you reference a variable in Terraform configuration?
Variables are referenced using the var.
prefix followed by the variable name:
resource "aws_instance" "example" {
instance_type = var.instance_type
// other configuration
}
14. What are the different variable types available in Terraform?
Terraform supports several variable types:
string
: Text valuesnumber
: Numeric valuesbool
: Boolean values (true or false)list
: Sequence of values of the same typemap
: Collection of key-value pairsset
: Collection of unique valuesobject
: Complex structure with attributestuple
: Sequence of elements with specific typesany
: Any type (default if type isn't specified)
15. How do you define outputs in Terraform?
Outputs are defined using the output
block:
output "instance_ip" {
description = "The public IP of the instance"
value = aws_instance.example.public_ip
}
16. What is the purpose of the terraform block?
The terraform
block is used to configure Terraform itself, including:
- Required Terraform version
- Required providers and their versions
- Backend configuration for state storage
- Experiments (for testing new features)
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
17. How do you use locals in Terraform and what are their benefits?
Locals are defined using the locals
block and can be referenced with local.
prefix:
locals {
common_tags = {
Environment = "production"
Project = "web-app"
}
}
resource "aws_instance" "example" {
tags = local.common_tags
}
Benefits of locals include reducing repetition, making complex expressions more readable, and avoiding repetition of the same values throughout configuration.
18. What is the difference between variables and locals in Terraform?
- Variables: Input parameters that can be set from outside the configuration (CLI, files, environment variables)
- Locals: Internal values defined within the configuration that can't be set from outside
19. How do you handle sensitive data in Terraform variables?
Sensitive data can be marked using the sensitive
argument:
variable "db_password" {
description = "Database administrator password"
type = string
sensitive = true
}
Terraform will redact this value from output and logs. For even more security, use secret management systems like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault.
20. What is data source in Terraform and how is it different from a resource?
A data source allows Terraform to fetch and use information defined outside of Terraform or in another Terraform configuration:
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
}
The key difference is that resources are managed by Terraform (created, updated, destroyed), while data sources are only read from and don't create or manage infrastructure.
21. How do you use conditional expressions in Terraform?
Conditional expressions use the syntax: condition ? true_val : false_val
resource "aws_instance" "example" {
instance_type = var.env == "prod" ? "m5.large" : "t2.micro"
// other configuration
}
22. What are dynamic blocks in Terraform?
Dynamic blocks allow you to dynamically construct repeatable nested blocks within a resource:
resource "aws_security_group" "example" {
name = "example"
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
23. How do you use the count parameter in Terraform?
The count
parameter creates multiple instances of a resource:
resource "aws_instance" "web" {
count = 3
ami = "ami-123456"
instance_type = "t2.micro"
tags = {
Name = "web-${count.index}"
}
}
24. How do you use the for_each parameter in Terraform?
The for_each
parameter creates multiple instances of a resource based on a map or set:
resource "aws_iam_user" "example" {
for_each = toset(["user1", "user2", "user3"])
name = each.value
}
25. What is the difference between count and for_each?
- count: Creates resources based on a number. Resources are identified by index, which can cause issues when removing items from the middle of the list.
- for_each: Creates resources based on a map or set. Each resource has a unique key, making it more stable when adding or removing items.
Commands & Workflow
26. What is the purpose of terraform init?
terraform init
initializes a working directory containing Terraform configuration files. It:
- Downloads and installs providers
- Sets up the backend for state storage
- Installs modules (if any are used)
- Initializes the working directory for use with Terraform
27. What is the difference between terraform plan and terraform apply?
- terraform plan: Creates an execution plan showing what actions Terraform will take to reach the desired state. It's a dry run that doesn't make any changes.
- terraform apply: Executes the actions proposed in a Terraform plan to create, update, or destroy infrastructure.
28. What is terraform validate and when should you use it?
terraform validate
checks whether a configuration is syntactically valid and internally consistent. It validates the configuration files without accessing any remote services. It should be used as part of CI/CD pipelines to catch errors before planning or applying.
29. What is terraform fmt and why is it important?
terraform fmt
rewrites Terraform configuration files to a canonical format and style. It's important because:
- Ensures consistent formatting across teams
- Makes code more readable
- Can be integrated into CI/CD pipelines to enforce style guidelines
30. What is terraform destroy and when would you use it?
terraform destroy
destroys all remote objects managed by a particular Terraform configuration. It should be used:
- When you want to tear down infrastructure that's no longer needed
- In development environments to clean up resources
- As part of a cleanup process
Note: Use with caution in production environments!
31. How do you use terraform taint and terraform untaint?
terraform taint
marks a resource as tainted, forcing it to be destroyed and recreated on the next apply. terraform untaint
removes the taint mark.
terraform taint aws_instance.example
terraform untaint aws_instance.example
Note: These commands are being deprecated in favor of the replace
option in newer Terraform versions.
32. What is terraform import and how do you use it?
terraform import
brings existing infrastructure under Terraform management. It requires:
- First, write a resource block for the resource you want to import
- Then run:
terraform import RESOURCE_TYPE.NAME ID
# Example: Import an existing EC2 instance
terraform import aws_instance.example i-1234567890abcdef0
33. What is terraform state and what commands are available for state management?
Terraform state is stored in a file that maps real-world resources to your configuration. Key state management commands include:
terraform state list
: Lists resources in the stateterraform state show
: Shows attributes of a resourceterraform state mv
: Moves items in the stateterraform state rm
: Removes items from the stateterraform state pull
: Pulls current state and outputs to stdoutterraform state push
: Updates remote state from a local state file
34. What is terraform refresh and when is it used?
terraform refresh
updates the state file against real resources. It reconciles the state with actual infrastructure, which can be useful when manual changes have been made to resources outside of Terraform. Note: In recent versions, this is automatically done as part of terraform plan
and terraform apply
.
35. How do you use the -target option in Terraform commands?
The -target
option allows you to focus Terraform operations on specific resources:
terraform apply -target=aws_instance.example
This is useful for debugging or making emergency changes, but should be used sparingly as it can create state inconsistencies.
36. What is terraform workspace and how do you use it?
Terraform workspaces allow you to manage multiple distinct sets of infrastructure resources with the same configuration. Commands include:
terraform workspace list
: List workspacesterraform workspace new NAME
: Create a new workspaceterraform workspace select NAME
: Switch to a workspaceterraform workspace delete NAME
: Delete a workspace
37. How do you handle Terraform command-line arguments for variables?
You can set variables via the command line using the -var
flag:
terraform apply -var="instance_type=t2.large" -var="environment=staging"
For multiple variables, you can use a variable file with the -var-file
flag:
terraform apply -var-file="production.tfvars"
38. What is the terraform graph command and what is it used for?
terraform graph
generates a visual representation of either a configuration or execution plan. The output is in DOT format, which can be used with GraphViz to create diagrams showing resource dependencies.
39. How do you use terraform output command?
terraform output
extracts the value of an output variable from the state file:
terraform output instance_ip
terraform output -json # Get all outputs as JSON
40. What is the purpose of the -auto-approve flag?
The -auto-approve
flag skips interactive approval of a plan before applying. It's useful in automated environments like CI/CD pipelines:
terraform apply -auto-approve
Warning: Use with caution as it applies changes without confirmation.
State Management
41. What is the purpose of the Terraform state file?
The Terraform state file (terraform.tfstate) is a JSON file that stores the state of the managed infrastructure. It's used to:
- Map real-world resources to your configuration
- Track metadata about the resources
- Improve performance for large infrastructures
- Determine the order of operations for creates, updates, and deletes
42. Why should you not commit the Terraform state file to version control?
You should not commit the state file to version control because:
- It may contain sensitive data (passwords, secrets)
- It can cause conflicts when multiple people work on the same infrastructure
- It doesn't work well with collaborative environments
- Remote state backends provide better solutions for team collaboration
43. What are the different backends available for storing Terraform state?
Terraform supports multiple backends for state storage:
- Local: Stores state on local filesystem (default)
- Remote: Terraform Cloud/Enterprise
- AWS S3: With optional DynamoDB for state locking
- Azure Storage Account: Azure Blob Storage
- Google Cloud Storage: GCS buckets
- HashCorp Consul: Consul key-value store
- HTTP: RESTful backend
44. What is state locking in Terraform and why is it important?
State locking prevents multiple users from modifying the Terraform state simultaneously, which could lead to corruption or inconsistent states. When enabled, Terraform will lock the state file during operations that modify state, preventing others from making changes at the same time.
45. How do you configure a remote backend in Terraform?
Remote backends are configured in the terraform block:
terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "path/to/my/state.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-state-lock"
encrypt = true
}
}
46. What happens when you lose your Terraform state file?
If you lose your state file:
- Terraform loses track of managed resources
- Running
terraform plan
may show that it wants to create all resources from scratch - You may need to manually import existing resources back into a new state file
- This highlights the importance of using remote backends with proper backup mechanisms
47. How can you recover from a lost state file?
Recovery options include:
- If using a remote backend, check if there are backups or previous versions
- Manually import resources using
terraform import
- Recreate the infrastructure from scratch (if non-critical)
- Use provider-specific tools to discover existing resources
48. What is terraform state mv used for?
terraform state mv
is used to move items in the state file. This is useful when:
- Refactoring configuration (renaming resources)
- Moving resources to different modules
- Fixing state file issues
terraform state mv aws_instance.foo aws_instance.bar
49. What is terraform state rm used for?
terraform state rm
is used to remove items from the state file without destroying the actual infrastructure. This is useful when:
- You want to stop managing a resource with Terraform but keep the resource
- Resources were imported by mistake
- Cleaning up state file cruft
50. How do you handle sensitive data in the state file?
To handle sensitive data in the state file:
- Use backend encryption (most remote backends support encryption at rest)
- Limit access to the state file using appropriate permissions
- Use tools like SOPS or Cloud provider KMS for additional encryption
- Mark sensitive variables with
sensitive = true
- Consider using external secret management systems instead of storing secrets in state
51. What is the difference between local and remote state?
- Local state: Stored on the local filesystem. Suitable for individual use but not for team collaboration.
- Remote state: Stored in a shared remote backend. Enables team collaboration, state locking, and often includes additional features like versioning and access controls.
52. How do you manage multiple environments with Terraform state?
Common approaches for managing multiple environments:
- Separate state files per environment (using different backend configurations)
- Terraform workspaces (though this has limitations for strongly separated environments)
- Directory structure separation (different directories for each environment)
- Using a CI/CD system that handles environment-specific state
53. What are the best practices for Terraform state management?
Best practices include:
- Always use remote state for team collaboration
- Enable state locking to prevent corruption
- Regularly backup your state files
- Limit access to state files using appropriate permissions
- Use encryption for state files containing sensitive data
- Avoid manual modifications to the state file
54. How can you view the current state without modifying it?
You can use these commands to view state without modification:
terraform show
: Human-readable output of the current stateterraform state list
: List all resources in the stateterraform state show RESOURCE_ADDRESS
: Show attributes of a specific resourceterraform output
: View output values
55. What is a partial configuration for a backend?
A partial backend configuration omits some required arguments, which must be provided by other means (command line, environment variables, or interactively). This is useful for keeping sensitive information out of version control:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "network/terraform.tfstate"
}
}
Then provide the region via command line: terraform init -backend-config="region=us-east-1"
Providers & Modules
56. What is a Terraform provider?
A Terraform provider is a plugin that implements resource types for a specific infrastructure platform (cloud provider, SaaS service, etc.). Providers are responsible for understanding API interactions and exposing resources.
57. How do you configure a provider in Terraform?
Providers are configured using a provider
block:
provider "aws" {
region = "us-east-1"
profile = "production"
}
You can also configure providers using environment variables:
export AWS_ACCESS_KEY_ID="anaccesskey"
export AWS_SECRET_ACCESS_KEY="asecretkey"
export AWS_REGION="us-west-2"
58. What is the difference between required_providers and provider blocks?
- required_providers: Specifies which providers are needed and their version constraints (in the terraform block)
- provider blocks: Configures settings for a specific provider instance
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
59. How do you use multiple configurations of the same provider?
You can use multiple configurations of the same provider by using alias:
# Default provider configuration
provider "aws" {
region = "us-east-1"
}
# Additional configuration with alias
provider "aws" {
alias = "west"
region = "us-west-2"
}
# Reference the aliased provider
resource "aws_instance" "example" {
provider = aws.west
# ... other configuration
}
60. What is a Terraform module?
A Terraform module is a self-contained package of Terraform configurations that are managed as a group. Modules are the main way to package and reuse resource configurations in Terraform. A module can be as simple as a single resource or as complex as a multi-tier application architecture.
61. What are the benefits of using modules?
- Reusability: Write once, use multiple times.
- Organization: Keep related parts of your infrastructure together.
- Encapsulation: Hide the complexity of infrastructure behind a simple interface.
- Consistency: Ensure that infrastructure components are configured consistently across different environments.
62. How do you use a module from the Terraform Registry?
You use a module
block and specify the source from the registry:
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "3.14.2"
name = "my-vpc"
cidr = "10.0.0.0/16"
// ... other variables
}
63. How do you pass variables to a module?
You pass variables as arguments within the module
block. These arguments must correspond to variable declarations in the module's own configuration.
64. How do you get outputs from a module?
You can access a module's output values using the syntax module.MODULE_NAME.OUTPUT_NAME
.
# In the module's outputs.tf
output "vpc_id" {
value = aws_vpc.this.id
}
# In the root module
resource "aws_instance" "example" {
vpc_security_group_ids = [module.vpc.vpc_id]
}
65. What is the difference between a root module and a child module?
- Root Module: The main set of configuration files in the working directory where you run Terraform commands.
- Child Module: A separate directory of configuration files called by a root module or another child module.
66. What is the `source` attribute in a module block?
The source
attribute tells Terraform where to find the source code for the desired child module. This can be a local path, a Git repository, or the Terraform Registry.
67. How do you version modules?
You can use the version
attribute in the module block to constrain the module to a specific version or a range of versions. This is highly recommended for stability.
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 3.0" # Use any version >= 3.0 and < 4.0
}
68. What are the best practices for writing reusable modules?
- Keep modules focused on a single concern.
- Use variables for customization and provide sensible defaults.
- Use outputs to expose important information.
- Provide clear documentation (README, variable descriptions).
- Use versioning to manage changes.
69. What is the Terraform Registry?
The Terraform Registry is a public repository of Terraform modules and providers. It allows users to easily find, use, and share reusable infrastructure components.
70. How do you publish a module to a private registry?
You can use Terraform Cloud or Terraform Enterprise to host a private module registry. The process involves structuring your module correctly, versioning it with Git tags, and then publishing it to your organization's private registry.
Expressions & Functions
71. What are some common built-in functions in Terraform?
- String functions:
format
,join
,split
,upper
,lower
- Collection functions:
length
,element
,lookup
,contains
,keys
,values
- Numeric functions:
min
,max
,pow
,ceil
,floor
- Encoding functions:
jsonencode
,base64encode
- Filesystem functions:
file
,templatefile
- Network functions:
cidrsubnet
,cidrhost
72. How do you use the `lookup` function?
The lookup
function retrieves the value of a single element from a map, given its key. It allows for a default value if the key is not found.
# lookup(map, key, default)
lookup({a="ay", b="bee"}, "a", "default") # returns "ay"
lookup({a="ay", b="bee"}, "c", "default") # returns "default"
73. How do you use the `length` function?
The length
function returns the number of elements in a list, map, or set, or the number of characters in a string.
length([1, 2, 3]) # returns 3
length("hello") # returns 5
74. How do you use the `element` function?
The element
function retrieves a single element from a list at the given index. It wraps around if the index is larger than the list size.
element(["a", "b", "c"], 1) # returns "b"
element(["a", "b", "c"], 3) # returns "a" (wraps around)
75. How do you use the `cidrsubnet` function?
The cidrsubnet
function calculates a subnet address within a given IP network address range (CIDR prefix).
# cidrsubnet(prefix, newbits, netnum)
cidrsubnet("10.0.0.0/16", 8, 2) # returns "10.0.2.0/24"
76. What are splat expressions?
Splat expressions provide a more concise way to get a list of all the attributes of a given name from a list of complex objects.
# Instead of this:
output "instance_ids" {
value = [for s in aws_instance.server : s.id]
}
# Use this:
output "instance_ids" {
value = aws_instance.server[*].id
}
77. How do you use `for` expressions?
for
expressions allow you to transform a complex type into another complex type, often with filtering or transformation of elements.
# Create a map of instance IDs to public IPs
output "instance_ips" {
value = {
for instance in aws_instance.server : instance.id => instance.public_ip
}
}
78. What is the difference between `try` and `can` functions?
try
: Evaluates a series of expressions and returns the result of the first one that doesn't produce an error.can
: Evaluates an expression and returns a boolean indicating whether it was successful (true) or produced an error (false).
79. How do you perform string interpolation in Terraform?
String interpolation is done using the ${...}
syntax within a string.
"Hello, ${var.name}!"
80. How do you handle complex data structures with functions?
You can combine functions to process complex data. For example, to get a list of all subnet IDs from a VPC module output:
output "subnet_ids" {
value = values(module.vpc.private_subnets)
}
Terraform Cloud & Enterprise
81. What is Terraform Cloud?
Terraform Cloud is a managed service offering by HashiCorp that provides collaboration features, remote state management, and a consistent environment for running Terraform.
82. What are the key features of Terraform Cloud?
- Remote state management and locking
- Version control system integration (GitHub, GitLab, etc.)
- Private module registry
- Policy as Code with Sentinel
- Secure variable storage
- Team management and access controls
83. What is the difference between Terraform Cloud and Terraform Enterprise?
- Terraform Cloud: A multi-tenant, SaaS offering hosted by HashiCorp.
- Terraform Enterprise: A self-hosted, private instance of Terraform Cloud for organizations with strict security and compliance requirements.
84. What are Sentinel policies in Terraform?
Sentinel is a policy-as-code framework integrated into Terraform Cloud/Enterprise. It allows you to define and enforce policies on Terraform configurations before they are applied, such as restricting instance types, enforcing tagging conventions, or limiting costs.
85. What is a private module registry?
A private module registry, provided by Terraform Cloud/Enterprise, allows organizations to host and share their own internal Terraform modules securely, promoting reuse and consistency within the organization.
Advanced Topics & Best Practices
86. How do you manage dependencies between resources in Terraform?
Terraform automatically infers dependencies between resources based on references in the configuration. For example, if an EC2 instance references a security group, Terraform knows to create the security group first. For implicit dependencies, you can use the depends_on
meta-argument.
87. What is the `depends_on` meta-argument?
The depends_on
meta-argument explicitly specifies hidden dependencies between resources that Terraform cannot automatically infer. This forces a specific creation order.
resource "aws_instance" "example" {
# ...
depends_on = [aws_iam_role_policy.example]
}
88. What are provisioners and when should they be used?
Provisioners are used to execute scripts on a local or remote machine as part of resource creation or destruction. They should be used as a last resort when there is no other way to configure a resource, as they are not declarative and can make Terraform configurations more brittle.
89. What is the difference between local-exec and remote-exec provisioners?
local-exec
: Executes a command on the machine running Terraform.remote-exec
: Executes a command on the remote resource after it's created (requires SSH or WinRM access).
90. Why are provisioners considered a last resort?
Provisioners are not declarative and can introduce complexity and unpredictability. It's generally better to use configuration management tools like Ansible or cloud-init scripts for software configuration, and use Terraform solely for provisioning infrastructure.
91. How do you test Terraform code?
Testing strategies include:
- Linting and Formatting: Use
terraform fmt
and tools like TFLint. - Validation: Use
terraform validate
. - Unit/Integration Testing: Use frameworks like Terratest to write automated tests that provision real infrastructure and verify its state.
- Static Analysis: Use tools like Checkov or tfsec to scan for security misconfigurations.
92. What is Terratest?
Terratest is a Go library that provides patterns and helper functions for writing automated tests for your infrastructure code. It allows you to write tests that deploy real infrastructure, verify it's working correctly, and then tear it down.
93. How do you structure a large Terraform project?
Best practices for structuring large projects include:
- Using a modular approach with a clear directory structure
- Separating environments (dev, staging, prod) into different state files or directories
- Using a central repository for shared modules
- Using a consistent naming convention
94. What are some common Terraform best practices?
- Use remote state with locking
- Version your modules and providers
- Keep modules small and focused
- Use variables for customization and locals for readability
- Run
terraform fmt
andterraform validate
in CI - Avoid hardcoding values
95. How do you handle breaking changes in providers or modules?
To handle breaking changes:
- Pin provider and module versions to avoid unexpected updates
- Read the changelogs carefully before upgrading
- Test upgrades in a non-production environment first
- Use a gradual rollout strategy for upgrades
96. What is the `lifecycle` block and what are its uses?
The lifecycle
block is a meta-argument that customizes the lifecycle of a resource. Key uses:
create_before_destroy
: Creates the replacement resource before destroying the old one (useful for zero-downtime updates).prevent_destroy
: Prevents Terraform from accidentally destroying a critical resource.ignore_changes
: Tells Terraform to ignore changes to certain resource attributes.
97. What is the difference between `create_before_destroy` and `prevent_destroy`?
create_before_destroy
: Changes the update behavior to create a new resource before deleting the old one.prevent_destroy
: Acts as a safety net to prevent a resource from being destroyed at all.
98. How do you manage secrets in Terraform?
Best practices for managing secrets:
- Do not store secrets in plain text in your configuration or state files.
- Use environment variables or a secrets management system like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault.
- Use the
sensitive
argument for variables and outputs.
99. What are some common pitfalls to avoid when using Terraform?
- Managing state locally in a team environment
- Not using version control
- Hardcoding values instead of using variables
- Making manual changes to infrastructure outside of Terraform
- Overusing provisioners
100. What is the future of Terraform and IaC?
The future of Terraform and IaC includes:
- Deeper integration with cloud-native technologies like Kubernetes
- More sophisticated policy-as-code and governance features
- AI-assisted code generation and optimization
- Better support for multi-cloud and hybrid-cloud environments
- Increased focus on security and compliance automation