2023 Top Terraform Interview Questions and Answers - IQCode

Overview of Terraform

Terraform is a powerful infrastructure as code (IaC) tool that enables efficient and secure building, editing, and versioning of infrastructure. It works with both high-level and low-level components, including memory, compute instances, and networking, and has the ability to manage both third-party and in-house solutions.

Configuration files are used by Terraform to define the necessary components for running applications or entire data centers. Terraform is used by various cloud service providers such as Amazon Web Services, Google Cloud, IBM Cloud, Microsoft Azure, DigitalOcean, Oracle Cloud Infrastructure, OVH, OpenStack, Platform, OpenNebula, and VMware vSphere.

Terraform Interview Questions for Beginners

1. What are the main features of Terraform?

Solution: Some of the key features of Terraform include infrastructure as code, modularity, versioning, provider support, and cloud-agnosticism. Terraform is known for its ability to enable declarative infrastructure management, it is modular, making it simple to use and adapt, it supports versioning, which helps in managing infrastructure at scale, it is provider-agnostic and can be used with numerous cloud service providers.

2. What is Terraform's state file, and why is it important?

Solution: Terraform's state file records the current state of deployed infrastructure. It is an important feature of Terraform because it enables the tool to determine what changes are required in the infrastructure, as well as the exact modifications that have been made over time, allowing for easy resource management.

3. Why is Terraform called an infrastructure as code tool, and what benefits does it offer?

Solution: Terraform is referred to as an infrastructure as code tool because it allows the entire IT infrastructure to be defined and managed as code. This provides numerous benefits, including the ability to automate infrastructure deployment, make infrastructure changes safely, efficiently, and quickly, and simplify infrastructure management.

4. Describe the basic workflow of using Terraform.

Solution: The basic workflow for using Terraform involves creating a configuration file, applying this configuration to set up infrastructure, validating the changes and exporting the infrastructure output. This sequence is then repeated as needed in order to fully manage the required infrastructure.

5. What is Terraform's role in infrastructure orchestration, and how does it differ from other tools?

Solution: Terraform's role in infrastructure orchestration is to provide a standard way of managing infrastructure that has been built using various tools. Terraform's differentiating factor is that it allows infrastructure to be managed from end-to-end in a single workflow, whereas other tools often require the use of separate workflows for each individual infrastructure change.

Use Cases of Terraform

Terraform is a tool for building, changing, and versioning infrastructure. It enables developers to create and manage infrastructure as code in a variety of cloud platforms such as AWS, Google Cloud, and Microsoft Azure. Below are some common use cases for Terraform:

  • Creating Virtual Machines: Terraform can be used to create virtual machines, including their associated networking and storage resources, in a repeatable and consistent manner.
  • Deploying Applications: Deployment of applications on virtual machines or containers can also be automated with Terraform. Developers can use Terraform to create environments and deploy applications in a repeatable and consistent manner.
  • Multi-Cloud and Hybrid Cloud Infrastructure: Terraform can be used to manage infrastructure on multiple cloud providers or on-premises data centers. This makes it possible to create hybrid cloud architectures that span multiple clouds and locations.
  • Infrastructure Testing: Terraform can be used to test infrastructure changes before deployment. By creating infrastructure as code, developers can run tests on the code itself to ensure that the code is functioning as expected.
  • Managing Infrastructure State: Terraform keeps track of all the resources it creates, as well as the relationships between those resources. This makes it easy to understand the current state of the infrastructure and to make changes in a safe and controlled manner.

Is it Possible to Use Callbacks with Terraform for Azure?

Is it possible to utilize callbacks in Terraform on Azure? For instance, can we send a callback to a logging system, trigger, or other events?

Let's explore this possibility.

Terraform Init in the Context of Terraform

When we talk about Terraform, 'terraform init' refers to the first command that we run when working with a new or existing Terraform codebase. Its main purpose is to initialize a new Terraform working directory or an existing one after cloning it from version control.

During 'terraform init', Terraform downloads and installs all the necessary dependencies and plugins required to manage the infrastructure. It also initializes the backend used to store the Terraform state file, which contains the current status of the infrastructure managed by Terraform.

Running 'terraform init' is a crucial step that must be performed before running any Terraform command in a new or existing codebase.

Reasons Why Terraform Is Preferred as a DevOps Tool

Terraform is a popular infrastructure automation tool in the DevOps world. It is preferred for several reasons:

  1. Multi-Cloud Support: Terraform can be used to manage infrastructure across multiple cloud providers like AWS, Azure, and Google Cloud Platform. This means users can manage resources from different cloud providers with the same configuration language.
  2. Infrastructure as Code: Terraform allows creating and managing infrastructure through code. This makes it easier to version control infrastructure changes and apply best practices like code review.
  3. Declarative Language: Terraform uses a declarative language that describes the desired state of infrastructure. It allows users to define the resources they need and their configurations, and Terraform does the rest.
  4. Modularity: Terraform allows for the creation of reusable modules and code snippets for infrastructure management. This makes it easier to manage complex infrastructure by breaking it down into smaller, more manageable parts.
  5. Consistency: Terraform ensures consistency in infrastructure by applying the same code across different environments like development, staging, and production. This minimizes errors and potential downtime.

Overall, Terraform simplifies the process of managing infrastructure while promoting best practices in infrastructure management.

Major Competitors of Terraform

Terraform, an infrastructure as code tool, has various competitors in the market. Some of the major ones are:

1. CloudFormation by Amazon Web Services (AWS) 2. Ansible by Red Hat 3. Puppet 4. Chef 5. SaltStack

Each of these tools has its own unique features and capabilities, and the choice ultimately depends on the specific needs of the project or organization.

What is your understanding of Terraform Cloud?

As an AI language model, I don't have personal understanding. However, Terraform Cloud is a service offered by HashiCorp that allows users to collaborate on Terraform infrastructure plans, store and version control them in a centralized location, and deploy them to the cloud. It provides an interface for managing Terraform modules, state management, and remote execution. It also offers features such as access controls, policy enforcement, and notification systems for easier collaboration and efficient infrastructure management.

Explanation of the destroy command in Terraform

The destroy command in Terraform is used to completely remove the infrastructure created by a particular Terraform configuration. This command is very useful when you want to destroy your infrastructure.

When you execute the destroy command in your terminal, Terraform will read the state file that it generated during the creation of the infrastructure and execute the deletion of all resources that were created.

It is important to note that execution of the destroy command cannot be undone, so you should be very careful when using it. It is also recommended that you verify with team members before executing this command to avoid accidentally deleting important infrastructure.

To use the destroy command, simply run the command "terraform destroy" in your terminal within the directory which contains the Terraform configuration files.

Understanding Terraform Modules

Terraform modules are reusable codes that can be included in different Terraform configurations. They help in creating infrastructure that can be shared across different projects and teams. Modules can be designed to do tasks like creating servers, load balancers, databases, etc. They are self-contained and can be used to implement a specific function or application. With Terraform modules, infrastructure can be created in a modular way, which makes it easier to maintain and scale.

Benefits of using modules in Terraform

Modules are reusable, standalone components in Terraform that can be used to organize and share infrastructure resources. Using modules provides several benefits:

  1. Modularity: Modules allow you to break down your infrastructure into small, easily maintainable components, making your code more organized and easier to manage.
  2. Abstraction: Modules provide a way to abstract complex infrastructure constructs into simple, easy-to-understand components, simplifying code and reducing errors.
  3. Reuse: Modules can be used across multiple Terraform configurations and even across teams, making it easier to share infrastructure code.
  4. Testing: Modules can be tested in isolation, making it easier to identify and fix issues.
  5. Versioning: Modules can be versioned, making it easier to track changes and roll back if necessary.

Using modules is considered a best practice in Terraform, and it can greatly improve the efficiency and maintainability of your infrastructure code.

Guidelines for Using Terraform Modules

When using Terraform modules, it is important to follow certain guidelines to ensure proper functionality. Here are some guidelines to keep in mind:

- Use appropriate module naming conventions that accurately describe the module's purpose. - Clearly define module inputs and outputs, including their types and descriptions. - Make sure modules are properly tested before use in production environments. - Version control modules to ensure that changes are properly tracked and can be rolled back if needed. - Avoid hard-coding sensitive information such as passwords and API keys in module code. - Consider using module registries such as the Terraform Registry to easily share and manage modules. - Properly document modules to ensure consistency and ease of use for future developers. - Use modules for repeatable tasks and avoid unnecessary complexity.

Explanation of null_resource in the context of Terraform

In Terraform, a null_resource is a resource type that is used to execute arbitrary actions. It is often used for running local provisioners or executing custom scripts that are not directly supported by other Terraform resource types.

The null_resource has no physical infrastructure associated with it, so it does not create or manage any resources. Instead, it serves as a placeholder that executes the configured actions and then reports a change to Terraform, which can trigger other resources to be created or updated.

The null_resource can be defined using the following syntax:

resource "null_resource" "example" {
  # Configuration options go here

Within the configuration options, you can specify the actions to be executed using the provisioner blocks. For example:

resource "null_resource" "example" {
  provisioner "local-exec" {
    command = "echo Hello, World!"

This will execute the "echo Hello, World!" command on the local machine when the null_resource is created or updated.

Overall, the null_resource can be a useful tool in Terraform for executing custom scripts or other actions that are not directly supported by other resource types.

Explanation of the "terraform validate" command in the context of Terraform

The "terraform validate" command is used to check the syntax and configuration of Terraform files. It validates whether the code is correctly written and structured according to the syntax rules defined by the Terraform language.

This command checks if the syntax is valid and all the values and expressions used in the code are correct and reference valid objects. Terraform validate command also checks the configuration of the resources defined in the Terraform files and verifies if they meet the requirements and constraints of the provider and the target infrastructure.

This command is useful to validate the Terraform code before applying it to the infrastructure, detecting errors and preventing issues from arising. It saves time and ensures successful deployment of the resources.

Explanation of Terraform apply command in Terraform

In the context of Terraform, the command "terraform apply" is used to apply the changes to the infrastructure as defined in the configuration files. Terraform determines the difference between the current state of the infrastructure and the desired state specified in the configuration files. It then creates, modifies or destroys resources as needed to achieve the desired state.

Before applying changes, Terraform shows a preview of changes and prompts for confirmation unless the auto-approve flag is set. Once confirmed, Terraform applies the changes and updates the state accordingly. The state file is updated to reflect the new state of the infrastructure.

In short, "terraform apply" is the command that makes changes to the infrastructure according to the instructions specified in the configuration files.

Understanding the 'terraform version' command in Terraform

The 'terraform version' command is used in Terraform to display the current version of Terraform being used. This command is often used to verify that the correct version of Terraform is installed on the system before running any Terraform commands.

When executed, this command will display the version number of the Terraform executable installed on the system along with any additional build or commit information. It is important to keep the Terraform version up-to-date to ensure compatibility with new features and bug fixes.

Supported Version Control Tools in Terraform

Terraform supports several version control tools, including Git, Subversion (SVN), and Mercurial. These tools help manage changes to infrastructure as code by keeping track of versions and facilitating collaboration among team members. By leveraging version control, teams can easily work together and track changes made to their infrastructure over time.

Understanding Providers in the Context of Terraform

In Terraform, a Provider is responsible for interacting with an API to create, modify or delete resources. Providers are used to define infrastructure components, such as cloud resources, database instances, and monitoring tools.

Each provider has a set of resources and data sources which can be used to define infrastructure within Terraform's configuration files. When Terraform runs, it communicates with the provider’s API to create or modify resources based on the configuration files.

For example, if you're provisioning a resource in Amazon Web Services (AWS), Terraform will use the AWS provider to communicate with the AWS API to create or modify the resource. Similarly, if you're using Google Cloud Platform, you would use the Google Cloud provider.

In summary, Providers in Terraform allow you to easily manage your infrastructure by providing access to the APIs of various services and platforms in a standardized way.

Workflow of Terraform Core

Terraform is a tool for infrastructure as code that allows the creation and management of various resource types across multiple cloud providers. Below is an explanation of how the workflow of the core Terraform works:

  1. Configuration: The configuration files in Terraform are written in HashiCorp Configuration Language (HCL). The configuration specifies the resources to be created and their properties.
  2. Planning: Terraform creates a plan by analyzing the configuration and determining which resources need to be created, modified, or deleted. The plan shows the changes that will be made, providing an opportunity to review before applying.
  3. Execution: Once the plan is reviewed and approved, Terraform will proceed to execute the changes and create or update the resources in the desired state.
  4. Resource State Management: Terraform stores the current state of the resources in a state file to compare it with the desired state in the configuration. This helps Terraform to identify if any changes are needed in the next run.
  5. Destruction: If the infrastructure is no longer required, Terraform can destroy the resources and remove them from the state file.

By following this workflow, Terraform ensures that the infrastructure is created and managed consistently and that the desired state is always maintained.


# Configuration file in HCL

resource "aws_instance" "web_server" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = "web-server"

Terraform Interview Questions for Experienced

Question 19: Can you explain the architecture of Terraform request flow?

Terraform architecture follows a client-server architecture, with requests being sent from the client to the server to be processed.

The client is the command-line interface that executes commands in the Terraform configuration files.

The server is responsible for providing the infrastructure services to the clients. The server executes the commands from the client and communicates with the provider APIs to create, update or delete resources.

The provider APIs interact with the cloud platform, such as AWS or Azure, to execute the operations requested by the Terraform server.

In summary, the client sends requests to the Terraform server, which then communicates with the provider APIs to carry out the requested infrastructure actions.

Differences between Terraform and CloudFormation

Terraform and CloudFormation are two popular infrastructure-as-code tools used to create and manage resources on cloud platforms. Here are some key differences between the two:

  • Supports multiple cloud platforms including AWS, Azure, Google Cloud, and more
  • Uses its own configuration language called HashiCorp Configuration Language (HCL)
  • Allows for more flexibility in resource creation and management
  • Can create a plan showing proposed changes before applying them
  • Can be used with other tools in the Terraform ecosystem, such as Terragrunt for module management
  • Specifically designed for use with AWS
  • Uses JSON or YAML for configuration
  • Integrates well with other AWS services and resources
  • Provides more granular control over IAM permissions
  • Offers a graphical user interface for resource management in the AWS Management Console

Ultimately, the choice between Terraform and CloudFormation depends on a team's specific needs and preferences, as both tools have their strengths and weaknesses.

Explanation of Terraform Taint Command

The Terraform taint command is used to mark a Terraform-managed resource as "tainted," which means it should be destroyed and recreated on the next Terraform appliy action. This command is useful when you want to force recreation of a specific resource without having to destroy and recreate all resources in the infrastructure.

To use the taint command, you need to specify the resource you want to taint, like this:

terraform taint aws_instance.example

In the above example, "aws_instance.example" is the name of the resource you want to taint. Once you run this command, Terraform will mark the resource as tainted, and it will be destroyed and recreated when you run Terraform apply again.

It's important to note that tainting a resource does not automatically update any other resources that depend on it. You will need to run Terraform plan and Terraform apply again to ensure that the tainted resource is correctly recreated and any dependent resources are updated as needed.

Difference between Terraform and Ansible

Terraform and Ansible are both popular automation tools used in the field of DevOps. However, they have different use cases and approaches to automation.

Terraform is an infrastructure provisioning tool that allows you to define your infrastructure as code using a declarative language. This means you can define your infrastructure configuration using a high-level syntax that describes what you want to achieve, without worrying about how to achieve it. Terraform supports cloud providers such as AWS, Azure, Google Cloud, and more.

Ansible, on the other hand, is a configuration management tool that focuses on automating the configuration of systems. It uses a procedural language to define tasks and steps required to configure a system. During execution, Ansible connects to the system being configured and executes the defined tasks. Ansible supports both Linux and Windows operating systems, and can also be used for automation of cloud environments.

In summary, Terraform is for infrastructure provisioning, while Ansible is for system configuration. Depending on your use case, you may need to use one or both tools.

# Example Terraform configuration for provisioning an AWS EC2 instance

provider "aws" {
  region = "us-west-2"

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance"


A Virtual Private Cloud (VPC) is a virtual network dedicated to a specific AWS account. It provides logically isolated sections of the AWS Cloud for resources to be launched in. With VPC, you can select your IP address range, create subnets, and configure route tables and network gateways.

In Terraform, the command to use a VPC service is "terraform import aws_vpc.vpc ". This command imports the existing VPC into your Terraform configuration. Then, you can use the VPC resource in Terraform to build and manage your infrastructure.

Terraform FMT Command

The Terraform FMT command is used to reformat your Terraform configuration files to follow the formatting rules defined by Terraform. This command can be run on a single configuration file or on an entire directory of configuration files.

The formatting rules defined by Terraform include guidelines for indentation, line breaks, and other whitespace characters. By following these formatting rules, your configuration files will become more readable and easier to maintain.

To use the Terraform FMT command, simply navigate to the directory containing your configuration files and enter the following command:

terraform fmt

This will reformat all of the configuration files in the current directory and any subdirectories.

It is recommended to run the Terraform FMT command before committing any changes to your configuration files to ensure that they are properly formatted and uniform across your team's codebase.

Terraform and Terragrunt

Terragrunt is a thin wrapper that provides extra functionality to Terraform. Terragrunt helps to manage multiple Terraform modules, environments, and states. It enables you to maintain the standard DRY (Don't Repeat Yourself) pattern by keeping all configurations under version control.

Terragrunt has several use cases, such as:

- Managing multiple modules - Managing multiple environments - Simplifying remote state management - Locking state files for non-concurrent usage - Managing dependencies among modules - Supporting multiple AWS accounts

By using Terragrunt, you can simplify Terraform configuration code and make it more organized and efficient.

State File Locking in the Context of Terraform

The state file in Terraform contains the current state of the infrastructure being managed. Terraform uses this file to keep track of resources, configurations, and dependencies. Since this file is critical to the functioning of Terraform, it is important that it is not modified or accessed by multiple users or processes at the same time. This is where state file locking comes into play.

State file locking is a mechanism that is used to prevent multiple processes or users from reading and writing to the state file simultaneously. It ensures that only one process has access to the state file at any given time, preventing conflicts and ensuring that the state remains consistent.

Terraform provides two methods of state file locking:

  • Consul
  • DynamoDB

These are external systems that Terraform uses to store and manage locks. When Terraform starts executing a plan, it first tries to acquire a lock on the state file. If the lock is already held by another process, Terraform waits until the lock is released before proceeding. State file locks are automatically released by Terraform when it completes executing a plan.

Using state file locking is highly recommended in production environments where multiple users or processes may be working with the same state file. It helps prevent data loss and ensures consistency of the state between different runs of Terraform.

Understanding Terraform Core

Terraform Core is an open-source tool aiming to automate infrastructure provisioning for various types of services. It allows you to define a high-level configuration of your infrastructure as code, thus enabling you to manage your infrastructure efficiently.

The primary responsibilities of Terraform Core include managing the lifecycle of the infrastructure and its dependencies, tracking the configuration changes, and applying these changes to the underlying infrastructure. Terraform Core supports multiple cloud providers and services, allowing you to manage diverse infrastructure setups using a single tool.

In addition, Terraform Core provides a powerful command-line interface and a vast collection of plugins for integration with various systems, which makes it a versatile and flexible infrastructure management tool.

Controlling and Handling Rollbacks in Terraform

Rollbacks can be necessary in Terraform when something goes wrong during the infrastructure deployment process. To control and handle rollbacks in Terraform, you can use the following approach:

1. Use the "terraform plan" command to review the changes that Terraform plans to apply to your infrastructure before applying them.

2. If the plan looks correct and you want to proceed with the deployment, use the "terraform apply" command to apply the changes.

3. If a problem occurs during the deployment, Terraform will automatically attempt to roll back the changes to their previous state.

4. If the automatic rollback fails, you can use the "terraform taint" command to manually mark a resource for recreation, and the "terraform state rm" command to remove a resource from the Terraform state.

5. After making the necessary changes to fix the problem, use the "terraform apply" command to apply the corrected changes to your infrastructure.

6. Finally, use the "terraform destroy" command to de-provision the entire infrastructure when it is no longer needed.

By following these steps, you can effectively control and handle rollbacks in Terraform and ensure that your infrastructure is always in a stable and working state.

Procedures to Make a High-Level Object Available Between Modules

To make a high-level object from one module available to another module, we can follow these steps:
1. Import the module containing the desired object using the import keyword.
2. Use the dot notation to access the object from the imported module.
3. The object is now available to use in the current module.
4. Ensure that the object is public or has been made available for use by other modules.

# Example: importing a class named MyClass from module my_module

import my_module

obj = my_module.MyClass() # Accessing class MyClass from the my_module 
                          # and creating an object of it.

Understanding Remote Backends in the Context of Terraform

In the context of Terraform, a remote backend is an external service that stores the state information of infrastructure. When Terraform manages multiple resources, the state information can become complex and difficult to manage. A remote backend stores the state information remotely, making it easier to manage, share, and collaborate between teams. It can also increase the security of the infrastructure because only authorized users have access to the state information. Terraform supports a variety of remote backend options such as Amazon S3, Azure Storage, Google Cloud Storage, and HashiCorp Consul.

Preventing Duplicate Resource Error in Terraform

When working with Terraform, duplicate resource errors can occur when attempting to create two separate resources with the same name. To prevent this error, you can use certain methods like:

1. Naming conventions: Utilize a consistent naming convention for all resources to prevent any naming conflicts.

2. Resource dependencies: Define resource dependencies in the Terraform configuration to ensure that the creation of resources occurs in the correct order.

3. Terraform State: Keep track of the state of your infrastructure using Terraform State and regularly refreshing the state file to prevent errors.

By following these best practices, you can prevent duplicate resource errors and ensure that your Terraform infrastructure is stable and accurate.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.