Top Terraform Interview Questions You Need to Know

Prepare for your next Terraform interview with confidence by exploring our comprehensive guide on “Terraform Interview Questions and Answers for Freshers/Experienced.” This article is designed to help both beginners and seasoned professionals understand the key concepts and practical skills needed for success in Terraform interviews.

We cover a range of topics, from basic Terraform concepts and commands to advanced use cases and troubleshooting techniques. Whether you’re just starting with Terraform or looking to sharpen your expertise, our detailed questions and answers will provide valuable insights and examples to enhance your preparation. Discover essential Terraform knowledge and practical tips that will set you apart in any interview setting.

Terraform is an open-source infrastructure-as-code (IaC) tool developed by HashiCorp that allows users to define and manage infrastructure in a declarative configuration language. With Terraform, you can create, modify, and version your infrastructure in a consistent and automated manner across various cloud platforms, data centers, and services. It supports popular cloud providers like AWS, Azure, Google Cloud, and many others, making it ideal for managing multi-cloud or hybrid cloud environments.

Key Highlights of Terraform:

  • Declarative Language (HCL): Users describe the desired state of their infrastructure, and Terraform automatically handles provisioning and updates.
  • Multi-Cloud Support: Allows you to work with multiple cloud providers, enabling consistent infrastructure management across platforms.
  • Infrastructure as Code: Promotes versioning, collaboration, and automation, allowing teams to treat infrastructure like code.
  • State Management: Terraform maintains the state of your infrastructure, allowing it to make incremental changes and ensure consistency.
  • Plan and Apply: Offers a preview feature to see the proposed changes before applying them, reducing the chance of errors.

Terraform is a popular choice in the DevOps ecosystem, enabling infrastructure automation, consistency, and scalability.

terraform interview questions for experienced

Terraform Interview Questions

Q1. What is Terraform?
Ans: Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows users to define and provision infrastructure using a high-level configuration language. Terraform enables the management of cloud services, virtual machines, networks, and other resources through code. For example, you can use Terraform to define an AWS EC2 instance and its associated settings in a .tf configuration file, and then deploy it using Terraform commands.

Q2. What is Terraform provider?
Ans: A Terraform provider is a plugin that allows Terraform to interact with cloud providers, SaaS providers, and other APIs. Providers are responsible for managing the lifecycle of resources and exposing their functionalities to Terraform. For instance, the AWS provider allows Terraform to create, update, and manage AWS resources like EC2 instances, S3 buckets, and IAM roles.

Q3. Define IAC?
Ans: Infrastructure as Code (IaC) is a practice of managing and provisioning computing infrastructure through machine-readable configuration files rather than physical hardware configuration or interactive configuration tools. IaC allows for automated and consistent infrastructure management. For example, using Terraform to define your infrastructure in code allows you to automate the setup of a cloud environment consistently across different environments.

Q4. How does Terraform handle dependencies between modules?
Ans: Terraform handles dependencies between modules through its implicit dependency management. When you reference outputs from one module in another module, Terraform automatically understands the dependency and ensures that the required module is applied first. For instance, if Module A outputs a VPC ID and Module B requires that VPC ID to create subnets, Terraform will ensure Module A is applied before Module B.

Q5. What do you mean by Terraform init?
Ans: terraform init is a command used to initialize a Terraform configuration. It sets up the working directory for Terraform operations by downloading provider plugins, initializing backend configuration, and preparing the environment for further commands. For example, running terraform init will download the necessary plugins and prepare the configuration to run terraform plan or terraform apply.

Q6. Are callbacks possible with Terraform on Azure?
Ans: Terraform does not natively support callbacks, as it is primarily designed for declarative infrastructure management. However, you can integrate Terraform with other tools and services to achieve similar functionality. For example, you could use Azure Functions or Azure Logic Apps to trigger actions in response to changes made by Terraform.

Q7. How does Terraform handle secrets and sensitive data?
Ans: Terraform manages sensitive data through the use of variables marked as sensitive and by storing state files securely. Sensitive variables can be defined in Terraform configuration and are not displayed in logs or console output. Additionally, Terraform state files should be stored in a secure backend, such as Azure Storage or AWS S3 with encryption, to prevent unauthorized access. For example, using sensitive = true in a variable definition hides its value from Terraform’s output.

Q8. What are the key features of Terraform?
Ans:

  • Declarative Configuration: Allows defining infrastructure using a high-level language.
  • Provider Ecosystem: Supports multiple cloud providers and services through plugins.
  • State Management: Tracks the state of resources to manage updates and changes.
  • Modularization: Facilitates reuse and organization of code through modules.
  • Dependency Management: Automatically handles dependencies between resources and modules.

Q9. Define null resource in Terraform?
Ans: A null resource in Terraform is a resource type that does not create any real infrastructure but can be used to trigger actions or execute local commands. It is often used for tasks like running scripts or commands based on changes in the configuration. For example, a null_resource with a local-exec provisioner can be used to execute a shell script whenever the resource is applied.

Q10. What are the most useful Terraform commands?
Ans:

  • terraform init: Initializes a Terraform working directory.
  • terraform plan: Prepares an execution plan by comparing the current state to the desired configuration.
  • terraform apply: Applies the changes required to reach the desired state.
  • terraform destroy: Destroys all resources managed by the configuration.
  • terraform validate: Validates the configuration files for syntax and internal consistency.

Q11. Name some major competitors of Terraform?
Ans:

  • AWS CloudFormation: A service for defining AWS resources using JSON or YAML.
  • Azure Resource Manager (ARM) Templates: A tool for deploying Azure resources using JSON templates.
  • Google Cloud Deployment Manager: A service for managing Google Cloud resources using YAML or JSON.

Q12. What are the reasons for choosing Terraform for DevOps?
Ans:

  • Multi-Cloud Support: Terraform can manage resources across various cloud providers.
  • Infrastructure as Code: Facilitates version control and automation of infrastructure management.
  • Modularity: Allows for reusable and organized configuration through modules.
  • Strong Community and Ecosystem: Provides a wide range of providers and modules from the community.

Q13. How to check the installed version of Terraform?
Ans: To check the installed version of Terraform, you can use the command terraform version. This command displays the current version of Terraform along with any installed provider versions. For example, running terraform version might return Terraform v1.3.0.

Q14. What do you understand by Terraform in AWS?
Ans: Terraform in AWS refers to using Terraform to manage and provision AWS resources. With Terraform, you can define AWS infrastructure components such as EC2 instances, S3 buckets, and RDS databases in code, and then apply these configurations to create and manage AWS resources. For example, a Terraform configuration might define an EC2 instance and its associated security group and IAM roles.

Q15. How does Terraform handle secrets and sensitive data?
Ans: Terraform handles secrets and sensitive data by marking variables as sensitive, which prevents their values from being displayed in logs and output. Additionally, it is important to secure the Terraform state file, which contains sensitive information, by using encrypted backends such as AWS S3 with server-side encryption or Azure Storage with encryption.

Q16. Describe how you can use Terraform with infrastructure deployment tools like Ansible or Chef?
Ans: Terraform can be used in conjunction with infrastructure deployment tools like Ansible or Chef to manage different aspects of the infrastructure. Terraform is typically used for provisioning the infrastructure (e.g., creating VMs, networks), while Ansible or Chef handle configuration management and application deployment. For example, you can use Terraform to provision EC2 instances in AWS, and then use Ansible to configure those instances by installing software and setting up configurations.

Q17. Explain Oracle Cloud Infrastructure?
Ans: Oracle Cloud Infrastructure (OCI) is a cloud computing service provided by Oracle Corporation. OCI offers a range of cloud services including computing, storage, networking, and database services. It is designed to support enterprise applications and workloads with high performance and reliability. For example, OCI provides services like Oracle Autonomous Database and Oracle Cloud Compute, which can be managed and provisioned using Terraform.

Q18. What is the purpose of Terraform’s “null_resource,” and when would you use it?
Ans: The null_resource in Terraform is used to execute arbitrary actions or commands that are not tied to actual infrastructure. It can be used to run scripts or commands during the provisioning process. For example, you might use a null_resource with a local-exec provisioner to execute a script that performs some configuration or setup tasks after Terraform has provisioned the resources.

Q19. How can you handle resource failures and retries in Terraform?
Ans: Terraform does not have built-in mechanisms for handling resource failures and retries directly. However, you can manage retries and handle failures by using retry logic in external scripts or tools that interact with Terraform. Additionally, you can use the depends_on attribute to manage dependencies and ensure resources are created in the correct order. For retries, consider using provisioning tools like Ansible, which have built-in retry capabilities.

Q20. Describe how to use Terraform’s “locals” block for conditional expressions?
Ans: The locals block in Terraform allows you to define local variables that can be used within your configuration. Conditional expressions can be used within the locals block to set values based on conditions. For example, you can use a conditional expression to set a local variable based on the environment:

locals {
  environment = var.environment == "production" ? "prod" : "dev"
}

In this example, local.environment will be set to “prod” if var.environment is “production,” otherwise it will be “dev.”

Q21. What is Terraform’s “force-unlock” command used for?
Ans: The terraform force-unlock command is used to manually unlock the Terraform state file if it becomes locked due to a failed or interrupted operation. This command is necessary when Terraform cannot automatically release the lock on the state file, preventing further operations. For example, if a terraform apply command was interrupted, you might need to run terraform force-unlock to manually release the lock.

Q22. What is the difference between Terraform’s “destroy” and “refresh” commands?
Ans:

  • terraform destroy: This command is used to destroy all resources defined in the Terraform configuration. It will remove all infrastructure that was created by Terraform. For example, running terraform destroy will terminate all EC2 instances, delete all S3 buckets, and remove other resources.
  • terraform refresh: This command updates the state file with the current state of resources as they exist in the infrastructure. It does not make changes to the infrastructure but ensures that the state file is up-to-date. For example, if a resource was modified outside of Terraform, running terraform refresh will update the state file to reflect those changes.

Q23. How can you use Terraform to manage infrastructure across multiple cloud providers simultaneously?
Ans: Terraform supports managing infrastructure across multiple cloud providers by using multiple provider configurations within the same configuration file. Each provider block specifies the credentials and configuration for a different cloud provider. For example, you can configure both AWS and Azure providers in the same Terraform configuration to provision resources in both clouds:

provider "aws" {
  region = "us-east-1"
}

provider "azurerm" {
  features {}
}

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "West Europe"
}

Q24. Explain the concept of Terraform providers and their role in resource provisioning?
Ans: Terraform providers are plugins that enable Terraform to interact with various APIs and services. Providers manage the lifecycle of resources by defining the necessary API calls and configurations. They are responsible for creating, updating, and deleting resources. For example, the AWS provider allows Terraform to manage AWS resources like EC2 instances and S3 buckets, while the Azure provider manages Azure resources.

Q25. Explain the uses of Terraform CLI and list some basic CLI commands?
Ans: The Terraform CLI (Command Line Interface) is used to interact with Terraform configurations and manage infrastructure. Basic CLI commands include:

  • terraform init: Initializes a working directory containing Terraform configuration files.
  • terraform plan: Prepares an execution plan by comparing the current state to the desired configuration.
  • terraform apply: Applies the changes required to reach the desired state.
  • terraform destroy: Destroys all resources managed by the configuration.
  • terraform validate: Validates the configuration files for syntax and internal consistency.

Terraform Interview Questions for Experienced

Q26. Describe how to use Terraform’s “locals” block for creating reusable expressions?
Ans: The locals block in Terraform allows you to define variables that can be used throughout your configuration. These variables can include reusable expressions and calculations. For example, you can define a local variable for a common tag value used across multiple resources:

locals {
  common_tags = {
    Environment = "production"
    Project     = "my_project"
  }
}

resource "aws_instance" "example" {
  tags = local.common_tags
}

In this example, local.common_tags is used to apply consistent tags to an AWS instance.

Q27. What is the Terraform interpolation syntax, and how can you use it?
Ans: Terraform interpolation syntax allows you to reference variables, resource attributes, and outputs within strings and expressions. Interpolation is done using ${} syntax. For example:

output "instance_ip" {
  value = "The IP address is ${aws_instance.example.public_ip}"
}

In this example, ${aws_instance.example.public_ip} is replaced with the actual public IP of the AWS instance.

Q28. Explain the concept of Terraform’s “data” blocks and their use cases?
Ans: Terraform’s data blocks are used to retrieve and reference information from existing resources or data sources that are not managed by Terraform. Data sources allow you to query external systems and incorporate their data into your configuration. For example, you might use a data block to fetch information about an existing AWS AMI:

data "aws_ami" "latest_amazon_linux" {
  owners = ["amazon"]
  most_recent = true
  filters {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}

Q29. What are modules in Terraform?
Ans: Modules in Terraform are reusable configurations that group related resources together. Modules can be used to encapsulate and manage complex infrastructure setups. They can be sourced from local directories, remote repositories, or the Terraform Registry. For example, you might create a module for deploying a web server with its associated security groups and load balancers, which can then be reused across different environments.

Q30. How can you use the “depends_on” attribute in Terraform resource blocks?
Ans: The depends_on attribute in Terraform is used to explicitly specify dependencies between resources, ensuring that certain resources are created or destroyed in a specific order. This is useful when resources have implicit dependencies that Terraform might not automatically detect. For example:

resource "aws_security_group" "example" {
  name = "example_sg"
}

resource "aws_instance" "example" {
  depends_on = [aws_security_group.example]
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

In this example, the AWS instance will only be created after the security group has been created.

Q31. How to use the Terraform “output” block for exporting resource information?
Ans: The output block in Terraform is used to export information about resources that can be used by other configurations or to display data to the user. Outputs are useful for exposing resource attributes or values. For example:

output "instance_ip" {
  value = aws_instance.example.public_ip
}

In this example, the public IP address of the AWS instance is exported and can be accessed after the terraform apply command.

Q32. Describe how to use Terraform with infrastructure-as-a-service (IaaS) providers?
Ans: Using Terraform with IaaS providers involves defining infrastructure resources in Terraform configuration files and applying those configurations to provision resources with the IaaS provider. You start by configuring the appropriate provider (e.g., AWS, Azure, Google Cloud) and then define resources such as virtual machines, networks, and storage. For example, to use Terraform with AWS:

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

In this example, Terraform provisions an EC2 instance in AWS based on the provided configuration.

Q33. What do you understand about remote backend in the context of Terraform?
Ans: A remote backend in Terraform is a configuration that specifies where Terraform stores its state files. Instead of storing state locally, remote backends store the state file in a remote location, such as an AWS S3 bucket or Azure Storage. This facilitates collaboration and state management in team environments by providing centralized storage, versioning, and locking. For example:

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "terraform/state"
    region         = "us-east-1"
  }
}

Q34. Define Resource Graph in Terraform?
Ans: The Resource Graph in Terraform is a directed acyclic graph (DAG) that represents the dependencies between resources. It shows how resources depend on each other and determines the order in which Terraform should create, update, or delete resources. This graph is used by Terraform to generate an execution plan that respects these dependencies. For example, if a VM depends on a network, the network will be created first.

Q35. What procedures should be taken to make a high-level object from one module available to the other module?
Ans: To make a high-level object from one module available to another module, you need to use output values in the source module and reference these outputs in the consuming module. For example, if Module A outputs an IP address, Module B can use this output as an input:

Module A:

output "instance_ip" {
  value = aws_instance.example.public_ip
}

Module B:

module "module_a" {
  source = "./module_a"
}

resource "aws_something" "example" {
  ip_address = module.module_a.instance_ip
}

Q36. Explain State File Locking in the context of Terraform?
Ans: State file locking is a mechanism to prevent concurrent operations on the Terraform state file, ensuring that only one operation can modify the state at a time. This prevents race conditions and conflicts during state changes. For example, when using remote backends like AWS S3 with DynamoDB for locking, Terraform will acquire a lock on the state file before making changes and release it afterward.

Q37. How will you upgrade plugins on Terraform?
Ans: To upgrade plugins in Terraform, you need to run the terraform init command, which will automatically check for and download the latest versions of provider plugins specified in your configuration. If you need to upgrade to a specific version, you can modify the provider configuration with the desired version and then run terraform init again. For example:

provider "aws" {
  version = "~> 4.0"
}

Q38. Differentiate between Terraform and CloudFormation?
Ans:

  • Terraform: An open-source tool by HashiCorp for provisioning and managing infrastructure across multiple cloud providers using a declarative configuration language. It supports a wide range of providers and has a strong module system for reusability.
  • CloudFormation: A service by AWS for defining and provisioning AWS infrastructure using JSON or YAML templates. It is AWS-specific and tightly integrated with other AWS services but lacks support for multi-cloud environments.

Q39. Give the terraform configuration for creating a single EC2 instance on AWS?
Ans:

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
  
  tags = {
    Name = "ExampleInstance"
  }
}

Q40. How can you perform blue-green deployments using Terraform?
Ans: Blue-green deployments in Terraform can be achieved by managing two separate environments (blue and green) and switching traffic between them. You provision both environments in parallel, test the new environment, and then switch over. For example, you can define two sets of resources (blue and green) and update a load balancer to point to the new environment:

resource "aws_elb" "example" {
  instances = aws_instance.green.id
}

resource "aws_instance" "blue" {
  # Configuration for blue environment
}

resource "aws_instance" "green" {
  # Configuration for green environment
}

Q41. Explain the command terraform taint in the context of Terraform?
Ans: The terraform taint command marks a resource for recreation during the next terraform apply. This is useful when you want to force a resource to be destroyed and recreated, such as when a resource’s configuration has changed or it is in a corrupted state. For example:

terraform taint aws_instance.example

Q42. What do you know about Terraform core? What are the primary responsibilities of Terraform core?
Ans: Terraform core is the central component of Terraform responsible for processing configurations, managing state, and generating execution plans. Its primary responsibilities include:

  • Reading Configuration Files: Parsing and understanding the .tf configuration files.
  • Managing State: Keeping track of the current state of resources.
  • Generating Execution Plans: Comparing the current state to the desired state and creating a plan for applying changes.
  • Applying Changes: Communicating with providers to create, update, or delete resources.

Q43. Differentiate between Terraform and Ansible?
Ans:

  • Terraform: Focuses on provisioning and managing infrastructure through declarative configuration. It manages infrastructure lifecycle and supports multiple cloud providers.
  • Ansible: Primarily used for configuration management and application deployment. It is agentless and uses playbooks written in YAML to automate tasks on existing infrastructure.

Q44. Explain the command terraform fmt in the context of Terraform?
Ans: The terraform fmt command is used to format Terraform configuration files to a canonical format and style. It automatically formats the code according to Terraform’s conventions, making it more readable and consistent. For example, running terraform fmt on a configuration file will align the indentation and spacing.

Q45. What do you know about Terragrunt? What are its uses?
Ans: Terragrunt is a tool that works as a wrapper around Terraform to provide additional features for managing multiple Terraform configurations. It helps with:

  • Managing Multiple Terraform Modules: Simplifies configurations for complex infrastructures with multiple modules.
  • DRY Principles: Encourages reuse of configurations and reduces duplication.
  • Remote State Management: Provides features for managing remote state and locking.

Q46. Which command can be used to preview the terraform execution plan?
Ans: The terraform plan command is used to preview the execution plan before applying changes. It shows what actions Terraform will take to reach the desired state without actually making changes. For example:

terraform plan

Q47. What do you mean by a Virtual Private Cloud (VPC)? Which command do you use in Terraform to use a VPC service?
Ans: A Virtual Private Cloud (VPC) is a private network within a cloud provider’s environment that allows you to isolate and control network resources, such as subnets, IP addresses, and security groups. In Terraform, you define and manage VPCs using the aws_vpc resource. For example:

resource "aws_vpc" "example" {
  cidr_block = "10.0.0.0/16"
}

Q48. How can you prevent Duplicate Resource Error in Terraform?
Ans: To prevent duplicate resource errors in Terraform, ensure that each resource has a unique name or identifier within the same module. Avoid creating resources with the same name or type in the same configuration or module. You can also use the terraform state rm command to remove duplicates from the state file if they were created inadvertently. For example:

terraform state rm aws_instance.duplicate_instance

Q49. Does Terraform support multi-provider deployments?
Ans: Yes, Terraform supports multi-provider deployments. You can configure multiple providers in the same Terraform configuration to manage resources across different cloud providers or services simultaneously. For example, you can use AWS for compute resources and Azure for storage in the same configuration:

provider "aws" {
  region = "us-east-1"
}

provider "azurerm" {
  features {}
}

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "West Europe"
}

Q50. What are some of the built-in provisioners available in Terraform?
Ans: Terraform provides several built-in provisioners for executing scripts or commands on resources:

  • local-exec: Executes commands on the local machine where Terraform is running.
  • remote-exec: Executes commands on a remote resource, such as a VM, via SSH or WinRM.
  • file: Uploads files to the resource before running other provisioners.

For example, to run a script on an AWS EC2 instance using remote-exec:

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

  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx"
    ]
  }
}

Q51. Name all version controls supported by Terraform?
Ans: Terraform supports the following version controls for module sources:

  • Local Paths: Modules can be sourced from local directories.
  • Git: Modules can be sourced from Git repositories, including GitHub, GitLab, and Bitbucket.
  • HTTP/HTTPS: Modules can be sourced from HTTP or HTTPS URLs.
  • Terraform Registry: Modules can be sourced from the Terraform Registry, a public repository for Terraform modules.

Q52. How is duplicate resource error ignored during terraform apply?
Ans: Duplicate resource errors occur when multiple resources with the same name or ID are defined. To avoid or resolve these errors, ensure that each resource has a unique name and identifier within the configuration. You can also use the terraform state rm command to remove duplicate entries from the state file. For example:

terraform state rm aws_instance.duplicate_instance

Q53. Is Terraform usable for on-prem infrastructure?
Ans: Yes, Terraform can be used for managing on-premises infrastructure. While it is often associated with cloud environments, Terraform supports various on-premises providers and resources through plugins. For example, you can use Terraform with VMware, OpenStack, or other on-premises infrastructure solutions to manage virtual machines, networks, and storage.

Q54. Tell us about some notable Terraform applications?
Ans:Notable applications of Terraform include:

  • Infrastructure Provisioning: Automating the creation and management of cloud and on-premises resources.
  • Multi-Cloud Deployments: Managing resources across multiple cloud providers in a single configuration.
  • Infrastructure as Code (IaC): Defining and managing infrastructure using code for consistency and reproducibility.
  • Environment Management: Creating and managing multiple environments, such as development, staging, and production, with isolated configurations.

Q55. What is a Private Module Registry?
Ans: A Private Module Registry is a service or repository where organizations can store and manage their own Terraform modules privately. It allows teams to share reusable modules internally while keeping them secure and controlled. Terraform Enterprise and Terraform Cloud offer built-in support for private module registries, but organizations can also set up their own private registries using the Terraform Registry API.

Q56. Which command destroys Terraform managed infrastructure?
Ans: The terraform destroy command is used to destroy all resources managed by Terraform according to the configuration files. This command will remove all infrastructure created by the configuration and is often used to clean up resources when they are no longer needed. For example:

terraform destroy

Q57. What are the different degrees of Sentinel policing?
Ans: Sentinel provides policy-as-code capabilities in Terraform for enforcing compliance and governance. The degrees of Sentinel policing include:

  • Advisory: Policies provide recommendations or warnings without blocking actions.
  • Soft Mandatory: Policies block actions but allow them to be overridden with proper justification.
  • Hard Mandatory: Policies strictly enforce rules and prevent any non-compliant actions from being applied.

These degrees of policing help ensure infrastructure changes adhere to organizational policies and compliance requirements.

Click here for more related topics.

Click here to know more about Terraform.

About the Author