Terraform, an open-source infrastructure as code (IaC) tool by HashiCorp, has become a cornerstone for managing and automating cloud infrastructure. As organizations increasingly adopt multi-cloud strategies, Terraform’s ability to provision, manage, and version infrastructure efficiently across various platforms makes it an essential tool for DevOps and cloud engineers. If you're preparing for a Terraform interview, it’s crucial to understand both the fundamentals and the advanced features of the tool.
The popularity of tools like Terraform can be attributed to the rise of DevOps. If you wish to advance your career in the field of DevOps and other cloud-related technology, you will be encountering terraform, as you’ll be needing to answer terraform interview questions you must go through this article. This article will discuss the most essential terraform interview questions, so let’s get started!
Ans: Terraform is a DevOps application that helps us create infrastructure and cloud data centres while keeping track of what was created and where. It is a tool that helps us build infrastructure safely and efficiently. Terraform can manage both popular service providers and custom in-house solutions.
2. What steps comprise Terraform's core workflow?
Ans: Terraform's core workflow consists of three steps:
The first step is to write, which includes developing infrastructure in code (code framework).
The second step is to plan ahead to see how the changes will look before implementing them.
Finally, the third step is to apply, which is concerned with developing a repeatable infrastructure.
3. Discuss some critical features of Terraform.
Ans: Terraform assists us in dealing with our frameworks as code and developing them when required. The key features are:
A control centre that permits clients to notice capacities.
The capacity to interpret HCL code into JSON design.
A setup language that upholds the introduction.
A module count that monitors the number of modules applied to the frameworks.
4. What exactly is IAC?
Ans: This is one of the most basic and frequently asked terraform interview questions.IAC (Infrastructure as Code) enables you to build, change, and manage your infrastructure using code rather than manual processes. The configuration files are created based on the specifications of your infrastructure, and these configurations can be edited and distributed securely within an organisation.
5. When can we use the terraform init command?
Ans: We can use the terraform init command for the following cases:
Plugin Installation
Backend Initialization
Child Module Installation
6. What exactly is Terraform D, and how does it function?
Ans: Terraform D is a Windows plugin compatible with nearly all in-service systems. The terraform init looks for plugins in the following directory by default.
7. Can I add policies to Terraform Enterprise's open-source or pro versions?
Ans: Policies cannot be added to Terraform Enterprise's open-source description. The same is true for the Enterprise Pro edition. Terraform Enterprise's best version could only contact the watch policies.
8. What are Modules in Terraform?
Ans: A module in Terraform is a container for multiple resources used concurrently. Every Terraform that includes resources mentioned in .tf files requires the root module.
9. Is it possible to use Terraform with callbacks on Azure? Sending a callback to, say, a logging system, a trigger, or other events?
Ans: Yes. This can be accomplished using Azure Event Hubs. This feature is now available in the Terraform AzureRM provider. Terraform's Azure supplier offers users straightforward functionality. Microsoft Azure Cloud Shell includes a pre-configured Terraform occurrence.
10. What exactly do you mean by Terraform providers?
Ans: Providers are Terraform plugins that allow it to interact with cloud providers, SaaS providers, and other APIs. The terraform configurations must declare which providers they require for Terraform to install and use. Some Terraform providers require configuration before use, such as endpoint URLs or cloud regions.
11. What is the function of the Terraform provider?
Ans: The function of the terraform provider is as follows:
Terraform providers extend Terraform's ability to manage resource types and data sources.
Terraform service providers set up a specific infrastructure platform (either cloud or self-hosted).
A provider implements every resource type; Terraform cannot manage any infrastructure without providers.
Local utilities, for instance generating random numbers for unique resource names, can also be provided by Terraform providers.
12. What is the difference between terraform plan and terraform apply?
Ans:
terraform plan creates an execution plan, showing what actions Terraform will take to change your infrastructure to match the desired state defined in your configuration files. It doesn't make any actual changes.
terraform apply executes the actions proposed in the Terraform plan, making real changes to your infrastructure to align it with the desired state.
13. What is the Terraform state file?
Ans: The Terraform state file is a JSON file that stores the current state of the infrastructure managed by Terraform. It tracks the resources and their properties, helping Terraform understand what’s already provisioned and enabling efficient updates without recreating existing resources. The state file is crucial for maintaining synchronization between your configuration and actual infrastructure.
14. What is the purpose of the terraform.tfvars file?
Ans: The terraform.tfvars file is used to define variable values in Terraform. It allows you to separate your variable definitions from your main configuration files, making it easier to manage different environments or configurations without changing the core Terraform code.
15. How can you prevent Terraform from destroying a specific resource?
Ans: You can use the lifecycle block with the prevent_destroy argument set to true within a resource block. This will prevent Terraform from destroying the resource, even if you remove it from your configuration or run terraform destroy.
Intermediate-Level Terraform Interview Questions
16. Is it possible to deploy Terraform with multiple providers?
Ans: Yes, Terraform supports multi-provider deployments, including on-premises deployments such as Openstack and VMware and SDN management.
17. What exactly is a Terraform cloud?
Ans: The Terraform cloud is a platform that enables teams to collaborate on Terraform projects on-demand or in response to specific circumstances. It is inextricably linked to Terraform's processes and data. A private registry hosts Terraform modules.
18. Describe in detail Oracle Cloud Infrastructure.
Ans: Oracle Cloud is a cloud computing service that provides storage, servers, applications, services, and networks via a global network of managed data centers managed by Oracle Corporation. These services are available at all times via the Internet.
19. What exactly is a "terraform backend"?
Ans: Any Terraform setup can include a backend, which defines two key things:
Where are surgeries performed?
Where has the state been saved? (Terraform keeps track of all resources in a state file.)
20. Name all of Terraform's version controls.
Ans: The following version controls are supported:
Azure DevOps Services and Server
Bitbucket Cloud and Server
Gitlab EE and CE
Gitlab.com
GitHub Business
www.GitHub.com (OAuth)
21. How can you inject dependencies from modules other than .tfvars files or CLI arguments?
Ans: The default Terraform method would be to use remote-state to lookup the outputs of other modules. In the community, it is also common to use terragrunt, a tool for explicitly injecting variables between modules.
22. Explain the concept of a null resource in the context of Terraform.
Ans: The null resource allows you to create provisioners that aren't directly linked to any existing resource. Because a null resource behaves the same as any other resource, you can configure provisioners, connection details, and other meta-parameters the same way. This gives you more control over when provisioners in the dependency graph execute.
23. Can you give some examples of how Sentinel policies can be used?
Ans: Sentinels are a great way to use Terraform to apply various rules. A few examples are provided below:
Limit the cloud provider's capabilities.
Examine the audit trail of Terraform Cloud operations.
You can restrict how modules are used in the Private Module Registry.
Make clear ownership of resources a requirement.
Only specific resources, services, or data sources are forbidden.
Make resource labeling a requirement.
24. How do I write down a variable that changes due to an external source or during “Terraform apply”?
Ans: You use it as follows: variable "my_var" { }
25. What are the differences between Terraform Cloud and Terraform CLI?
Ans: The key differences between Terraform Cloud and Terraform CLI are:
Collaboration: Terraform Cloud enables multiple team members to work on the same infrastructure with integrated VCS (Version Control System) support.
Remote state storage: Terraform Cloud stores the state file remotely, eliminating the need for manual state management.
Workflows and Notifications: Provides advanced workflows, notifications, and governance through policies.
Execution Environment: Terraform Cloud executes plans and applies remotely, reducing the need for local resource consumption.
26. How can you use Terraform workspaces to manage multiple environments?
Ans: Terraform workspaces allow you to manage multiple distinct sets of infrastructure resources within a single configuration. Each workspace maintains its own state file, enabling you to create separate environments (e.g., development, staging, production) using the same Terraform code. You can create and switch between workspaces using commands like terraform workspace new, terraform workspace select, and reference the current workspace in your configuration using ${terraform.workspace}.
27. How do you handle drift in Terraform?
Ans: Drift in Terraform refers to changes made to infrastructure outside of Terraform’s control (e.g., manual changes in the cloud console). To handle drift, you can:
Use terraform plan: This checks for discrepancies between the actual state of infrastructure and the expected state defined in Terraform configurations.
Apply corrective measures: If drift is detected, run terraform apply to bring the infrastructure back to the desired state.
Implement drift detection: Use Terraform Cloud’s drift detection feature or integrate drift-checking scripts into CI/CD pipelines.
28. What is the purpose of the terraform import command?
Ans: The terraform import command is used to bring existing infrastructure resources under Terraform management. It allows you to import real-world resources that were created outside of Terraform into your Terraform state. This is useful when you want to start managing existing infrastructure with Terraform or when you need to recover from manual changes made outside of Terraform.
29. What are data sources in Terraform?
Ans: Data sources in Terraform allow you to query information about resources outside of your Terraform configuration or managed by other systems. They are useful for fetching data that you need to reference in your configuration, such as retrieving an existing VPC ID, AMI ID, or other information from the cloud provider.
Example:
data "aws_vpc" "default" {
default = true
}
The data source retrieves the default VPC in AWS and makes its ID available for use.
30. How do you upgrade Terraform to the latest version?
Ans: To upgrade Terraform to the latest version, follow these steps:
Download the latest version from the Terraform releases page.
Replace the old binary with the new one.
Run terraform -version to verify the installation.
If using a version manager like tfenv, you can run:
tfenv install latest
tfenv use latest
Advanced-Level Terraform Interview Questions
31. Which command can be used to see a preview of the Terraform execution plan?
Ans: Terraform plan command will generate the execution plan for the infrastructure changes Terraform will make.
32. In the Terraform cloud, which command is used to create new workspaces?
Ans: To create a new workspace, use the terraform workspace new<workspace-name> command.
33. Which command is used to validate the syntax of Terraform configuration files?
Ans: Terraform validate is used to check whether a configuration is syntactically correct and internally consistent.
34. Which command can be used to match the Terraform state to the actual real-world infrastructure?
Ans: To reconcile Terraform state with actual real-world infrastructure, use the terraform apply -refresh-only command. It is the new replacement for the terraform refresh command, which is now deprecated.
35. Highlight some come differences between Terraform and Ansible.
Parameters
Terraform
Ansible
Purpose
Primarily used for Infrastructure as Code (IaC) to provision and manage infrastructure resources.
Primarily used for Configuration Management, application deployment, and orchestration.
Language
Uses a declarative language (HCL - HashiCorp Configuration Language). You declare what the infrastructure should look like, and Terraform figures out how to achieve that state.
Uses imperative playbooks (YAML) where you explicitly define the steps to achieve the desired configuration.
Use Case
Best suited for managing infrastructure provisioning (e.g., creating virtual machines, networks, and databases).
Best suited for configuration management (e.g., installing packages, managing services, setting up environments).
State Management
Maintains state files to keep track of the infrastructure's current state, which helps with resource tracking and updates.
Does not require state management. It connects to hosts, runs tasks, and doesn’t store any state information.
Primarily used for configuration on existing infrastructure. It can provision resources, but it's not as extensive or seamless as Terraform for IaC.
Agent Requirement
Agentless: No need to install agents on managed nodes. Terraform directly interacts with cloud APIs.
Agentless: No agents are required on the managed hosts. Ansible uses SSH to connect and execute tasks.
Orchestration
Limited to infrastructure provisioning. Not designed for handling detailed orchestration of complex workflows across multiple systems.
Designed for complex orchestration tasks, such as deploying applications across multiple servers and managing service dependencies.
Provisioning
Infrastructure provisioning tool: Ideal for creating and managing infrastructure resources like VMs, networks, and databases.
Can be used for ad-hoc provisioning, but it’s mainly focused on configuring existing resources rather than provisioning.
Idempotency
Ensures idempotency by tracking state and applying changes only when the desired state is different from the current state.
Ensures idempotency by rerunning tasks only if changes are needed, but relies on checks defined in playbooks to avoid unnecessary actions.
Execution Model
Executes in phases: Plan, Apply, Destroy. Generates an execution plan before applying changes.
Executes task-by-task, where each step is run sequentially on the target systems. No pre-execution plan is generated.
36. How Does Terraform Store Sensitive Data?
Ans: Terraform requires credentials to communicate with your cloud provider's API. These credentials, however, are frequently saved in plaintext on your desktop. GitHub is exposed to thousands of API and cryptographic keys every day. As a result, never store your API keys directly in Terraform code. Use encrypted storage to store passwords, TLS certificates, SSH keys, and anything else that shouldn't be stored in plain text.
37. How would you recover from a failed Terraform application?
Ans: You can keep your configuration in version control and commit before each change, and then use the features of the version control system to revert to an earlier configuration if necessary. You must always recommit the previous version code in order for it to be the new version in the version control system.
38. How can you avoid duplicating resources in Terraform?
Ans: It can be done in one of three ways, depending on the situation and the need.
The Terraform code will no longer manage the resource if it is destroyed.
By removing API resources.
Importing action will also help with resource depletion.
39. What are some of Terraform Azure Provider's most recent considerations?
Ans: New data resources, such as Azure batch certificate, which aids in certificate administration, are included in recent editions. In networking, this resource is used to control the prefix. The Azure app service has been improved, and bugs have been addressed.
40. If something goes wrong, how will you manage and regulate rollbacks?
Ans: To make the previous code version the new and current one in your VCS, you must recommit it. This would launch the terraform run command, which would run the previous code. Because Terraform is more declarative, you'll make certain that everything in the code returns to its original state. If the state file was corrupted, you would suggest using Terraform Enterprise's State Rollback feature.
41. How do you resolve provider version conflicts in Terraform?
Ans: To resolve provider version conflicts, you can specify the required provider version in your provider block, using version constraints to lock down specific versions.
Example:
provider "aws" {
version = "~> 3.0"
}
This ensures that Terraform will use a version of the AWS provider in the 3.x range but not higher than 3.99.
42. How can you handle sensitive data in Terraform?
Ans: Terraform provides several ways to handle sensitive data:
Use input variables marked as sensitive: variable "password" { type = string sensitive = true }
Use environment variables: TF_VAR_password=mysecretpassword
Use encrypted backend storage (e.g., S3 with encryption)
Use external secret management systems like HashiCorp Vault
Use sensitive = true in output blocks to prevent sensitive data from being displayed in the console output
43. How do you manage dependencies between resources in Terraform?
Ans: Terraform automatically manages resource dependencies based on the configurations. However, you can explicitly define dependencies using the depends_on argument when needed.
In this example, the aws_instance will be created only after the aws_vpc.main resource has been successfully provisioned.
44. What is a dynamic block in Terraform and when would you use it?
Ans: A dynamic block in Terraform allows you to dynamically construct repeatable nested blocks within resource configurations. It's useful when you need to create multiple similar nested blocks based on a list or map of data. Dynamic blocks help reduce code duplication and make your configurations more flexible and maintainable. They are commonly used for creating multiple security group rules, IAM policy statements, or any other scenario where you need to generate multiple similar nested blocks.
45. How does terraform taint and terraform untaint work?
Ans:
1. terraform taint: Marks a resource for recreation in the next terraform apply. It’s used when you want to forcefully recreate a resource, even if no configuration changes were made.
Example:
terraform taint aws_instance.example
2. terraform untaint: Removes the taint on a resource, so it won’t be recreated in the next apply.
Example:
terraform untaint aws_instance.example
46. What is a remote backend in Terraform and why is it important?
Ans: A remote backend in Terraform is a configuration that allows you to store your Terraform state file in a remote, shared location instead of on the local filesystem. Remote backends are important for several reasons:
Collaboration: Multiple team members can access and work with the same state.
State locking: Prevents concurrent modifications to the same infrastructure.
Security: Sensitive data in the state file can be better protected.
Backup and versioning: Many remote backends provide built-in backup and versioning capabilities.
47. What is the difference between count and for_each in Terraform?
Ans: Both count and for_each allow you to create multiple instances of a resource in Terraform, but they differ in usage:
count: Creates multiple instances of a resource based on a single integer value. Resources are indexed numerically (e.g., aws_instance.example[0]).
for_each: Creates multiple instances of a resource based on a map or set. Resources are indexed by key, making it more flexible when dealing with collections of objects (e.g., aws_instance.example["key"]).
48. What are some best practices for writing and organizing Terraform code?
Ans: Some best practices for writing and organizing Terraform code include:
Use consistent formatting (use terraform fmt).
Separate your code into modules for reusability and maintainability.
Use remote backends for state management.
Version control your Terraform configurations.
Use variables and locals to make your code more flexible and readable.
Follow naming conventions for resources, variables, and modules.
Use data sources to fetch external information when possible.
Implement proper state management and locking mechanisms.
Use workspaces or file structures to manage multiple environments.
Regularly update Terraform and provider versions.
Implement automated testing for your Terraform code.
Use .tfvars files to separate variable values from your main configuration.
49. How can you import existing infrastructure into Terraform?
Ans: Terraform allows you to import existing infrastructure into its state file using the terraform import command. This is useful when managing resources that were created manually or by other tools.
This imports an AWS EC2 instance with the ID i-12345678 into the Terraform configuration aws_instance.my_instance.
50. How can you use Terraform to create reusable infrastructure components?
Ans: You can create reusable infrastructure components in Terraform by:
Creating modules: Encapsulate a set of resources into a reusable package.
Using input variables: Make your modules flexible and configurable.
Providing outputs: Allow other parts of your configuration to use information from the module.
Using locals: Define reusable expressions within a module.
Leveraging for_each and dynamic blocks: Create flexible, repeatable resource configurations.
Following DRY (Don't Repeat Yourself) principles in your configurations.
Frequently Asked Questions
What is Terraform?
Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp that enables users to define, provision, and manage infrastructure across multiple cloud platforms using a declarative configuration language called HCL (HashiCorp Configuration Language).
What are Terraform providers?
Terraform providers are plugins that allow Terraform to interact with various cloud platforms, services, and APIs. They manage the lifecycle of specific resources, enabling Terraform to create, update, and delete resources on platforms like AWS, Azure, GCP, and more.
Describe The Terraform Configuration Syntax
Terraform configuration syntax is declarative and written in HashiCorp Configuration Language (HCL). It consists of blocks, arguments, and expressions that define the desired state of resources, variables, providers, and outputs within infrastructure environments.
Differentiate between Terraform and CloudFormation
Terraform is a multi-cloud Infrastructure as Code tool supporting various providers, while AWS CloudFormation is a native IaC service specific to AWS. Terraform offers broader multi-cloud capabilities, whereas CloudFormation is tightly integrated with AWS services.
Conclusion
In this article, we discussed the most important terraform interview questions.
We hope this blog has helped you enhance your knowledge regarding terraform and will surely help you in terraform interviews. After reading about the terraform interview questions, are you not feeling excited to read/explore more articles? You can visit our interview blogs, can practice coding questions that are frequently asked in interviews, Infosys interview questions, DBMS interview questions, and much more.
But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems,interview experiences, and interview bundle for placement preparations.
Nevertheless, you may consider our paidcourses to give your career an edge over others!