30 Best Terraform Interview Questions to Master!

Prepare for your next job interview with our comprehensive guide to the Top Terraform Interview Questions. Whether you’re a beginner or an experienced professional, this guide covers essential questions and detailed answers that will help you excel.

Table of Contents

Terraform Interview Questions for Freshers

1. What is Terraform and How does Terraform work?

Terraform is an open-source Infrastructure as Code (IaC) tool used to automate the deployment, configuration, and management of service infrastructure.

Terraform operates in three main stages:

  1. Write – Define infrastructure using a declarative configuration language.
  2. Plan – Preview changes before applying.
  3. Apply – Execute the plan to manage infrastructure.

2. What is the Terraform Registry?

The Terraform Registry is a public repository of modules and providers used by Terraform to manage a wide array of infrastructure resources.

Terraform Registry

3. Explain the use of Terraform modules?

Modules in Terraform are containers for multiple resources that are used together. They enhance code reusability and maintainability.

The attribute “version” in the module can be specified in a terraform configuration file by using the terraform module registry as a source. Use ‘? ref’ to specify the branch, version, and query string if you are using the GitHub repository as a source.

4. What are Terraform providers and how do they function?

Providers in Terraform are plugins that allow Terraform to interact with cloud providers, SaaS providers, and other APIs. Each provider offers resources and data sources for managing specific types of infrastructure.

5. List all Terraform supported versions.

Below are the list of supported version:

  1. GitHub.com
  2. Bitbucket Cloud and Server
  3. GitLab.com
  4. GitLab CE and EE
  5. GitHub Enterprise
  6. Azure DevOps Server and Services

6. What is a “resource” in Terraform?

A resource in Terraform language represents one or more infrastructure objects, such as virtual networks, computes instances, or higher-level components like DNS records.

7. How does Terraform handle dependencies between resources?

Terraform automatically understands dependency relationships between resources and ensures all dependencies are created in a proper sequence.

8. What are variables in Terraform and why are they important?

Variables in Terraform are used to customize aspects of Terraform modules without altering the module’s own source code, facilitating flexible configurations.

Additionally, Set certain attributes while declaring input variables, as below:

  1. type — to identify the type of the variable being declared.
  2. default — default value in case the value is not provided explicitly.
  3. description — a description of the variable. This description is also used to generate documentation for the module.
  4. validation — to define validation rules.
  5. sensitive — a boolean value. If true, Terraform masks the variable’s value anywhere it displays the variable.

Terraform input  Input variables support multiple data types:

  • String
  • Object
  • Set
  • Number
  • Map
  • Tuple
  • List
  • Boll

9. How does Terraform use provisioners and when should they be used?

Provisioners in Terraform are used to execute scripts on a local or remote machine as part of resource creation or destruction. They should be used sparingly as they can lead to unpredictable Terraform behavior.

10. What is the significance of the Terraform plan command?

The terraform plan command is used to create an execution plan, which lets you preview what Terraform will do when you run terraform apply.

Below are the steps that you can perform:

(i) Navigate to your application infrastructure code – cd modernisation-platform-environments/terraform/environments/my-application

(ii) Run a Terraform init that assumes the backend role in the Modernisation Platform account – terraform init – backend

config=assume_role={role_arn=\"arn:aws:iam::000000000000:role/modernisation-account-terraform-state-member-access\"}

Remember to replace the 000000000000 placeholder with the Modernization Platform account ID.

(iii) View the workspaces (you have different workspaces for your different environment accounts) – terraform workspace list

(iv) Select the required workspace – terraform workspace select my-application-development

(v) Run a Terraform plan – terraform plan

11. Explain the purpose of the terraform output command.

The terraform output command is used to extract the value of an output variable from the state file. You can export structured data about your resources using the output values from Terraform. This data can be used as a data source for another Terraform workspace or to configure other components of your infrastructure using automation tools.

Another way to expose data from a child module to a root module is through outputs.

Usage: terraform output [options] [NAME]

The command-line flags are all optional. The following flags are available:

  • -json: If specified, the outputs are formatted as a JSON object, with a key per output. If NAME is specified, only the output specified will be returned. This can be piped into tools such as jq for further processing.
  • -raw: If specified, Terraform will convert the specified output value to a string and print that string directly to the output, without any special formatting.
  • -no-color: If specified, output won’t contain any color.
  • -state=path: Path to the state file. Defaults to “terraform.tfstate”. Ignored when remote state is used.

12. What does the terraform taint command do?

The terraform taint command manually marks a Terraform-managed resource as tainted, forcing it to be destroyed and recreated on the next application.

To accomplish the same result, use the terraform apply “-replace” option instead of this deprecated command.

Terraform Taint

In this instance, it would be simpler to replace just VM 1, the problem source, rather than rebuilding the entire infrastructure. The taint command in Terraform can be used to accomplish this. We notify Terraform about the problematic resource in the state file by indicating which resource should be marked as tainted.

Enter the following command into the terminal to mark the resource as tainted. To determine which resource needs to be marked as tainted, the taint command accepts the resource identifier as a parameter.

13. Can Terraform manage existing infrastructure?

Yes, Terraform can manage existing infrastructure by importing it into your Terraform state, allowing you to manage it with Terraform configurations.

14. What is the difference between Terraform and configuration management tools like Ansible?

Terraform is primarily an infrastructure orchestration tool, meant for provisioning and managing the lifecycle of infrastructure, whereas tools like Ansible are designed for configuring and managing the state of software on existing infrastructure.

Terraform Ansible

Terraform is a tool for provisioning.

Ansible is a tool for managing configurations.

It uses a declarative Infrastructure as Code methodology.

It takes a procedural method.

It’s ideal for orchestrating cloud services and building cloud infrastructure from the ground up.

It is mostly used to configure servers with the appropriate software and to update resources that have previously been configured.

By default, Terraform does not allow bare metal provisioning.

The provisioning of bare metal servers is supported by Ansible.

In terms of packing and templating, it does not provide better support.

It includes complete packaging and templating support.

15. How does Terraform handle secrets and sensitive data?

Terraform offers secure methods for managing confidential information. To ensure that sensitive values are not saved in plain text in configuration files or state, one method is to pass them at runtime via environment variables or input variables.

Utilizing third-party secret management systems, such HashiCorp Vault, to obtain private information while executing Terraform is an additional choice. These methods improve security by keeping secrets apart from the infrastructure code.

Terraform Interview Questions for Experienced

1. Explain the role of the Terraform Backend.

Terraform backend determines where state data is stored. This can be either locally or remotely, which helps in team environments by locking the state to prevent conflicts.

Terraform uses the local backend by default, which saves state as a plain file in the current working directory, if a configuration contains no backend blocks.

Terraform writes the backend configuration in plain text in two separate files.

  • The current working directory’s backend configuration is stored in the .terraform/terraform.tfstate file.
  • All plan files capture the information in .terraform/terraform.tfstate at the time the plan was created.This makes sure Terraform is implementing the plan on the appropriate infrastructure.

2. What are the most useful terraform commands?

1. terraform init:

  • Initializes a new or existing Terraform working directory.
  • Downloads and installs the required providers and modules.
  • Initializes the Terraform backend configuration.
				
					terraform init
				
			

2. terraform plan:

  • Generates an execution plan based on your Terraform configurations.
  • Shows what actions Terraform will take to achieve the desired state.
  • Useful for reviewing changes before applying them.
				
					terraform plan
				
			

3. terraform apply:

  • Applies the changes required to reach the desired state of the configuration.
  • Creates, updates, or deletes resources as necessary.
				
					terraform apply
				
			

4. terraform validate:

  • Validates the syntax and configuration of your Terraform files.
  • Checks for errors in your configurations without executing them.
				
					terraform validate
				
			

5. terraform destroy:

  • Destroys the Terraform-managed infrastructure.
  • Removes all the resources defined in your Terraform configuration.
				
					terraform destroy
				
			

6. terraform workspace:

  • Manages workspaces, allowing you to work with multiple distinct sets of resources within a single configuration.
				
					terraform workspace list
terraform workspace new <name>
terraform workspace select <name>
				
			

7. terraform import:

  • Imports existing infrastructure into your Terraform state.
  • Useful when you have existing resources managed outside of Terraform and want to manage them using Terraform.
				
					terraform import <resource_type>.<resource_name> <resource_id>
				
			

3. What is the terraform workspace and how is it used?

Terraform workspace can have its own set of resources, allowing you to manage different environments (like development, staging, and production) or different configurations for the same infrastructure.

Terraform Interview Questions (Terraform Workspace)
				
					variable "example_var" {
  default = {
    development = "dev_value"
    staging     = "staging_value"
    production  = "prod_value"
  }
}


output "example_output" {
  value = var.example_var[terraform.workspace]
}
				
			

Here’s how you can use Terraform workspaces:

  • Create a Workspace: You can create a new workspace using the terraform workspace new <name> command. For example, terraform workspace new development.
  • List Workspaces: To see a list of all available workspaces, you can use terraform workspace list.
  • Select a Workspace: You can switch between workspaces using the terraform workspace select <name> command. For example, terraform workspace select staging.
  • Use Workspace-specific Variables: Workspaces can use variables that are specific to that workspace. You can define these variables in your configuration files using conditional expressions based on the workspace name.
  • Apply Changes per Workspace: When you apply changes with terraform apply, Terraform applies the changes to the currently selected workspace. This allows you to manage different sets of resources independently.
  • State Management: Terraform maintains separate state files for each workspace. This ensures that each workspace’s resources are managed independently, preventing any unintended interactions between workspaces.
  • Destroy Resources: Similarly, when destroying resources with terraform destroy, it affects only the resources in the currently selected workspace.

4. Explain the use of dynamic blocks in Terraform.

Dynamic blocks are used to dynamically construct repeatable nested blocks in Terraform configurations. This is useful in scenarios where a configuration includes multiple similar blocks.

5. What is State File Locking?

State file locking is a mechanism used by Terraform to prevent concurrent modifications to the Terraform state file by multiple users or processes.

Here’s how state file locking works in Terraform:

  • Locking Mechanisms
  • Locking Behavior
  • Timeouts and Retries
  • Locking Configuration
				
					terraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket"
    key            = "terraform.tfstate"
    region         = "us-west-1"
    dynamodb_table = "terraform-state-lock-table"
    lock_timeout   = "10m"
  }
}

				
			

In this example, we’re using an S3 backend with DynamoDB locking. The dynamodb_table specifies the name of the DynamoDB table used for locking, and lock_timeout specifies the maximum time Terraform will wait to acquire a lock before timing out.

6. Discuss the lifecycle hooks in Terraform.

Lifecycle hooks in Terraform are used to customize the behavior of resources, such as preventing the destruction of a resource with prevent_destroy, or managing resource creation order with create_before_destroy.

7. How does Terraform integrate with CI/CD pipelines?

Terraform integrates into CI/CD pipelines by allowing automated testing and deployment of infrastructure changes, using commands like terraform apply which can be triggered automatically via pipeline tools.

  1. Version Control: Store your Terraform configurations alongside your application code in a version control system like Git. This ensures that infrastructure changes are tracked, reviewed, and versioned just like application code.
  2. Pipeline Configuration: Define a CI/CD pipeline configuration (e.g., using Jenkins, GitLab CI/CD, GitHub Actions, or Azure DevOps) that includes steps to initialize Terraform, plan changes, apply changes, and optionally destroy resources.
  3. Terraform Initialization: In the pipeline, run terraform init to initialize the Terraform working directory. This step downloads the necessary providers and modules defined in your configuration.
  4. Terraform Plan: Run terraform plan to generate an execution plan, which describes what Terraform will do to achieve the desired state defined in your configurations. This step allows you to review changes before they are applied.
  5. Automated Testing: Include automated tests in your pipeline to validate the provisioned infrastructure. This can include infrastructure testing tools or custom scripts that validate the configuration of resources.
Terraform Integration with CI/CD Pipelines

Here’s a simplified example of a GitLab CI/CD configuration that integrates Terraform:

				
					stages:
  - plan
  - apply


terraform:
  stage: plan
  script:
    - terraform init
    - terraform plan -out=tfplan
  artifacts:
    paths:
      - tfplan


terraform_apply:
  stage: apply
  script:
    - terraform apply tfplan
				
			

8. Discuss the significance of Terraform version constraints in a module.

Version constraints ensure that your Terraform configurations use a specific version of a Terraform provider or module, preventing compatibility issues with future versions.

9. How to handle state conflicts in Terraform in a team environment?

State conflicts can be managed by using remote state features that support locking (such as Terraform Cloud or AWS S3 with DynamoDB) to ensure only one person’s changes are applied at a time.

10. What is Terraform Cloud, and how does it enhance Terraform usage?

Terraform Cloud is a HashiCorp service that provides advanced features like team access controls, private module registry, and a consistent environment for running Terraform configurations.

11. Describe how to use Terragrunt in conjunction with Terraform.

Terragrunt is a wrapper tool that provides additional tools for working with Terraform configurations, making it easier to manage dependencies, remote state, and environment configuration.

Use cases:

  • Keep your Terraform code DRY
  • Use multiple AWS accounts.
  • Maintain a DRY remote state configuration.
  • Keep your CLI flags DRY
  • Run Terraform commands on multiple modules at the same time.

12. What are the common functions used in Terraform and their purposes?

Terraform includes built-in functions like lookup, max, min, and concat, which can be used within the configuration to perform operations on data.

13. Explain the process and benefits of using Terraform for multi-cloud deployments.

Terraform’s ability to handle multiple provider plugins allows for seamless management of resources across different clouds, enabling consistent workflows and reducing vendor lock-in.

14. Explain the architecture of Terraform request flow?

Architecture of Terraform Request Flow (Terraform Interview Questions)

Below are the points that will explain the request flow.

  1. Terraform CLI:
    • The Terraform Command-Line Interface (CLI) is the primary tool for interacting with Terraform.
    • You use the CLI to run commands like terraform init, terraform plan, terraform apply, and others to manage your infrastructure.
  2. Terraform Core:
    • Terraform Core is responsible for interpreting Terraform configurations and executing operations to manage infrastructure.
    • It includes the Terraform execution engine, which processes configurations, generates plans, and applies changes.
  3. Provider Plugins:
    • Providers are responsible for managing resources, such as virtual machines, databases, networks, and more, with cloud providers or other services.
    • Each provider is implemented as a plugin and communicates with the respective service’s API to create, read, update, and delete resources.
    • Providers are downloaded and installed by Terraform based on the configurations in your Terraform files.
  4. State File:
    • The Terraform state file (terraform.tfstate) stores the current state of your managed infrastructure.
    • It contains information about resources, their configurations, and metadata.
    • The state file is crucial for Terraform to track changes, plan updates, and manage resources.
  5. Backend:
    • The backend determines where the Terraform state file is stored.
    • Backends can be local, remote, or custom, and they manage the state file’s storage, locking, and retrieval.
    • Examples of backends include local file storage, Amazon S3, Azure Blob Storage, and Terraform Cloud.

15. How can Terraform’s performance be optimized in large-scale environments?

Performance can be optimized by structuring resources with modules, minimizing the use of provisioners, and using workspaces to manage different states of the infrastructure efficiently.

Conclusion

This guide to the top 30 Terraform interview questions and answers is designed to provide a solid foundation for your interview preparation. With a focus on both freshers and experienced professionals, it helps you understand and implement Terraform capabilities effectively.

Related Articles

Multiple Choice Questions

1. Which of the following commands is used to create an execution plan for Terraform?

  • a) terraform init
  • b) terraform plan
  • c) terraform apply
  • d) terraform validate

2. What is the default file extension for Terraform configuration files?

  • a) .tf
  • b) .tfv
  • c) .tconf
  • d) .tfstate

3. Which command is used to initialize a Terraform working directory?

  • a) terraform start
  • b) terraform apply
  • c) terraform init
  • d) terraform refresh

4. How does Terraform ensure the order of resource creation?

  • a) Using depends_on
  • b) Using resource_order
  • c) Using sequence
  • d) Terraform automatically detects dependencies

5. Which of the following statements about Terraform state is true?

  • a) It is not necessary to manage Terraform state.
  • b) Terraform state stores the bindings between Terraform-managed resources and real-world resources.
  • c) Terraform state only exists during execution.
  • d) Terraform does not use any state file.

6. What is the purpose of terraform import?

  • a) Importing modules from the Terraform Registry
  • b) Importing existing infrastructure into your Terraform state
  • c) Importing providers
  • d) Importing remote states

7. Which Terraform feature allows you to divide resources into reusable, logical groups?

  • a) Modules
  • b) State Files
  • c) Workspaces
  • d) Providers

8. Which Terraform command is used to remove resources managed by Terraform?

  • a) terraform remove
  • b) terraform clean
  • c) terraform delete
  • d) terraform destroy

9. Which file does Terraform use to lock provider versions?

  • a) main.tf
  • b) variables.tf
  • c) terraform.tfvars
  • d) terraform.lock.hcl

10. How can you provide values to variables defined in a Terraform configuration?

  • a) Using terraform.tfvars
  • b) Using environment variables
  • c) By specifying -var or -var-file flags in the command line
  • d) All of the above

11. What is the purpose of the terraform refresh command?

  • a) Reapply the configuration
  • b) Reinitialize the project
  • c) Update the state file with real-world infrastructure
  • d) Validate the configuration files

12. Which of the following can be used to store Terraform state securely and enable state locking?

  • a) Local file system
  • b) Terraform Cloud
  • c) HashiCorp Consul
  • d) All of the above

13. What is the function of the terraform taint command?

  • a) Mark a resource as dirty and force a new one to be created
  • b) Remove a resource from the state file
  • c) Change the resource type
  • d) Update the resource configuration

14. Which keyword is used to declare an output value in Terraform?

  • a) result
  • b) return
  • c) output
  • d) export

15. How can you define dependencies explicitly between resources in Terraform?

  • a) By specifying depends_on
  • b) By creating a dependency graph
  • c) By using resource_order
  • d) Dependencies are always implicit

16. Which of the following allows for version control and collaboration when using Terraform?

  • a) Workspaces
  • b) Modules
  • c) Local state files
  • d) Terraform Cloud

17. In which scenario would you use the terraform apply -auto-approve command?

  • a) To create a new module
  • b) To automatically approve the execution plan without manual confirmation
  • c) To initialize a working directory
  • d) To destroy infrastructure

18. What happens if you run terraform apply without running terraform init first in a new workspace?

  • a) Terraform will initialize automatically
  • b) Terraform will apply changes without errors
  • c) Terraform will throw an error
  • d) Terraform will refresh the state file

19. Which of the following Terraform backends supports state locking and consistency checking?

  • a) Local
  • b) S3 with DynamoDB
  • c) GitHub
  • d) FTP

20. How does Terraform handle sensitive information in the configuration?

  • a) By using the sensitive attribute
  • b) It encrypts all variables by default
  • c) Sensitive information cannot be stored in Terraform
  • d) By using the secure block

Frequently Asked Questions

  1. Examine the job description: To learn more about the precise Terraform knowledge and experience needed for the position, carefully read the job description.
  2. Emphasize Your Important Skills: Determine which of the essential Terraform skills are listed in the job description, then order your readiness appropriately.

DevOps teams mainly use Terraform, an IAC tool, to automate different infrastructure tasks. One of the primary uses of Terraform is the provisioning of cloud resources, for example. It is an open-source, cloud-independent provisioning tool developed by HashiCorp using the Go programming language.

Using reusable, shareable, human-readable configuration files, DevOps teams can automate infrastructure provisioning with HashiCorp Terraform, an infrastructure as code (IaC) software tool. Infrastructure provisioning in on-premises and cloud environments can be automated with this tool.

Yes, Terraform on Azure can make callbacks through Azure Event Hubs. The functionality required to integrate with Azure Event Hubs and initiate callbacks based on particular events is offered by Terraform’s AzureRM provider.